e57e52d74b6927e2d73ac7ebb4b01627591556b4
[blender.git] / source / blender / editors / interface / interface_ops.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2009 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation, Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_ops.c
27  *  \ingroup edinterface
28  */
29
30 #include <stdio.h>
31 #include <math.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_scene_types.h"
37 #include "DNA_screen_types.h"
38 #include "DNA_text_types.h" /* for UI_OT_reports_to_text */
39
40 #include "BLI_blenlib.h"
41 #include "BLI_math_color.h"
42 #include "BLI_math_vector.h"
43 #include "BLI_utildefines.h"
44
45 #include "BLF_api.h"
46 #include "BLF_translation.h"
47
48 #include "BKE_context.h"
49 #include "BKE_screen.h"
50 #include "BKE_global.h"
51 #include "BKE_text.h" /* for UI_OT_reports_to_text */
52 #include "BKE_report.h"
53
54 #include "RNA_access.h"
55 #include "RNA_define.h"
56
57 #include "BIF_gl.h"
58
59 #include "UI_interface.h"
60
61 #include "IMB_colormanagement.h"
62
63 #include "interface_intern.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 /* only for UI_OT_editsource */
69 #include "ED_screen.h"
70 #include "BKE_main.h"
71 #include "BLI_ghash.h"
72
73 #include "ED_image.h"  /* for HDR color sampling */
74 #include "ED_node.h"   /* for HDR color sampling */
75 #include "ED_clip.h"   /* for HDR color sampling */
76
77 /* ********************************************************** */
78
79 typedef struct Eyedropper {
80         struct ColorManagedDisplay *display;
81
82         PointerRNA ptr;
83         PropertyRNA *prop;
84         int index;
85
86         int   accum_start; /* has mouse been presed */
87         float accum_col[3];
88         int   accum_tot;
89 } Eyedropper;
90
91 static int eyedropper_init(bContext *C, wmOperator *op)
92 {
93         Scene *scene = CTX_data_scene(C);
94         Eyedropper *eye;
95         
96         op->customdata = eye = MEM_callocN(sizeof(Eyedropper), "Eyedropper");
97         
98         uiContextActiveProperty(C, &eye->ptr, &eye->prop, &eye->index);
99
100         if ((eye->ptr.data == NULL) ||
101             (eye->prop == NULL) ||
102             (RNA_property_editable(&eye->ptr, eye->prop) == FALSE) ||
103             (RNA_property_array_length(&eye->ptr, eye->prop) < 3) ||
104             (RNA_property_type(eye->prop) != PROP_FLOAT))
105         {
106                 return FALSE;
107         }
108
109         if (RNA_property_subtype(eye->prop) == PROP_COLOR) {
110                 const char *display_device;
111
112                 display_device = scene->display_settings.display_device;
113                 eye->display = IMB_colormanagement_display_get_named(display_device);
114         }
115
116         return TRUE;
117 }
118
119 static void eyedropper_exit(bContext *C, wmOperator *op)
120 {
121         WM_cursor_restore(CTX_wm_window(C));
122         
123         if (op->customdata)
124                 MEM_freeN(op->customdata);
125         op->customdata = NULL;
126 }
127
128 static int eyedropper_cancel(bContext *C, wmOperator *op)
129 {
130         eyedropper_exit(C, op);
131         return OPERATOR_CANCELLED;
132 }
133
134 /* *** eyedropper_color_ helper functions *** */
135
136 /**
137  * \brief get the color from the screen.
138  *
139  * Special check for image or nodes where we MAY have HDR pixels which don't display.
140  */
141 static void eyedropper_color_sample_fl(bContext *C, Eyedropper *UNUSED(eye), int mx, int my, float r_col[3])
142 {
143
144         /* we could use some clever */
145         wmWindow *win = CTX_wm_window(C);
146         ScrArea *sa;
147         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
148                 if (BLI_rcti_isect_pt(&sa->totrct, mx, my)) {
149                         if (sa->spacetype == SPACE_IMAGE) {
150                                 ARegion *ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
151                                 if (BLI_rcti_isect_pt(&ar->winrct, mx, my)) {
152                                         SpaceImage *sima = sa->spacedata.first;
153                                         int mval[2] = {mx - ar->winrct.xmin,
154                                                        my - ar->winrct.ymin};
155
156                                         if (ED_space_image_color_sample(sima, ar, mval, r_col)) {
157                                                 return;
158                                         }
159                                 }
160                         }
161                         else if (sa->spacetype == SPACE_NODE) {
162                                 ARegion *ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
163                                 if (BLI_rcti_isect_pt(&ar->winrct, mx, my)) {
164                                         SpaceNode *snode = sa->spacedata.first;
165                                         int mval[2] = {mx - ar->winrct.xmin,
166                                                        my - ar->winrct.ymin};
167
168                                         if (ED_space_node_color_sample(snode, ar, mval, r_col)) {
169                                                 return;
170                                         }
171                                 }
172                         }
173                         else if (sa->spacetype == SPACE_CLIP) {
174                                 ARegion *ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
175                                 if (BLI_rcti_isect_pt(&ar->winrct, mx, my)) {
176                                         SpaceClip *sc = sa->spacedata.first;
177                                         int mval[2] = {mx - ar->winrct.xmin,
178                                                        my - ar->winrct.ymin};
179
180                                         if (ED_space_clip_color_sample(sc, ar, mval, r_col)) {
181                                                 return;
182                                         }
183                                 }
184                         }
185                 }
186         }
187
188         /* fallback to simple opengl picker */
189         glReadBuffer(GL_FRONT);
190         glReadPixels(mx, my, 1, 1, GL_RGB, GL_FLOAT, r_col);
191         glReadBuffer(GL_BACK);
192 }
193
194 /* sets the sample color RGB, maintaining A */
195 static void eyedropper_color_set(bContext *C, Eyedropper *eye, const float col[3])
196 {
197         float col_conv[4];
198
199         /* to maintain alpha */
200         RNA_property_float_get_array(&eye->ptr, eye->prop, col_conv);
201
202         /* convert from display space to linear rgb space */
203         if (eye->display) {
204                 copy_v3_v3(col_conv, col);
205                 IMB_colormanagement_display_to_scene_linear_v3(col_conv, eye->display);
206         }
207         else {
208                 copy_v3_v3(col_conv, col);
209         }
210
211         RNA_property_float_set_array(&eye->ptr, eye->prop, col_conv);
212
213         RNA_property_update(C, &eye->ptr, eye->prop);
214 }
215
216 /* set sample from accumulated values */
217 static void eyedropper_color_set_accum(bContext *C, Eyedropper *eye)
218 {
219         float col[3];
220         mul_v3_v3fl(col, eye->accum_col, 1.0f / (float)eye->accum_tot);
221         eyedropper_color_set(C, eye, col);
222 }
223
224 /* single point sample & set */
225 static void eyedropper_color_sample(bContext *C, Eyedropper *eye, int mx, int my)
226 {
227         float col[3];
228         eyedropper_color_sample_fl(C, eye, mx, my, col);
229         eyedropper_color_set(C, eye, col);
230 }
231
232 static void eyedropper_color_sample_accum(bContext *C, Eyedropper *eye, int mx, int my)
233 {
234         float col[3];
235         eyedropper_color_sample_fl(C, eye, mx, my, col);
236         /* delay linear conversion */
237         add_v3_v3(eye->accum_col, col);
238         eye->accum_tot++;
239 }
240
241 /* main modal status check */
242 static int eyedropper_modal(bContext *C, wmOperator *op, wmEvent *event)
243 {
244         Eyedropper *eye = (Eyedropper *)op->customdata;
245         
246         switch (event->type) {
247                 case ESCKEY:
248                 case RIGHTMOUSE:
249                         return eyedropper_cancel(C, op);
250                 case LEFTMOUSE:
251                         if (event->val == KM_RELEASE) {
252                                 if (eye->accum_tot == 0) {
253                                         eyedropper_color_sample(C, eye, event->x, event->y);
254                                 }
255                                 else {
256                                         eyedropper_color_set_accum(C, eye);
257                                 }
258                                 eyedropper_exit(C, op);
259                                 return OPERATOR_FINISHED;
260                         }
261                         else if (event->val == KM_PRESS) {
262                                 /* enable accum and make first sample */
263                                 eye->accum_start = TRUE;
264                                 eyedropper_color_sample_accum(C, eye, event->x, event->y);
265                         }
266                         break;
267                 case MOUSEMOVE:
268                         if (eye->accum_start) {
269                                 /* button is pressed so keep sampling */
270                                 eyedropper_color_sample_accum(C, eye, event->x, event->y);
271                                 eyedropper_color_set_accum(C, eye);
272                         }
273                         break;
274                 case SPACEKEY:
275                         if (event->val == KM_RELEASE) {
276                                 eye->accum_tot = 0;
277                                 zero_v3(eye->accum_col);
278                                 eyedropper_color_sample_accum(C, eye, event->x, event->y);
279                                 eyedropper_color_set_accum(C, eye);
280                         }
281                         break;
282         }
283         
284         return OPERATOR_RUNNING_MODAL;
285 }
286
287 /* Modal Operator init */
288 static int eyedropper_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
289 {
290         /* init */
291         if (eyedropper_init(C, op)) {
292                 WM_cursor_modal(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
293
294                 /* add temp handler */
295                 WM_event_add_modal_handler(C, op);
296                 
297                 return OPERATOR_RUNNING_MODAL;
298         }
299         else {
300                 eyedropper_exit(C, op);
301                 return OPERATOR_CANCELLED;
302         }
303 }
304
305 /* Repeat operator */
306 static int eyedropper_exec(bContext *C, wmOperator *op)
307 {
308         /* init */
309         if (eyedropper_init(C, op)) {
310                 
311                 /* do something */
312                 
313                 /* cleanup */
314                 eyedropper_exit(C, op);
315                 
316                 return OPERATOR_FINISHED;
317         }
318         else {
319                 return OPERATOR_CANCELLED;
320         }
321 }
322
323 static int eyedropper_poll(bContext *C)
324 {
325         if (!CTX_wm_window(C)) return 0;
326         else return 1;
327 }
328
329 static void UI_OT_eyedropper(wmOperatorType *ot)
330 {
331         /* identifiers */
332         ot->name = "Eyedropper";
333         ot->idname = "UI_OT_eyedropper";
334         ot->description = "Sample a color from the Blender Window to store in a property";
335         
336         /* api callbacks */
337         ot->invoke = eyedropper_invoke;
338         ot->modal = eyedropper_modal;
339         ot->cancel = eyedropper_cancel;
340         ot->exec = eyedropper_exec;
341         ot->poll = eyedropper_poll;
342         
343         /* flags */
344         ot->flag = OPTYPE_BLOCKING;
345         
346         /* properties */
347 }
348
349 /* Reset Default Theme ------------------------ */
350
351 static int reset_default_theme_exec(bContext *C, wmOperator *UNUSED(op))
352 {
353         ui_theme_init_default();
354         WM_event_add_notifier(C, NC_WINDOW, NULL);
355         
356         return OPERATOR_FINISHED;
357 }
358
359 static void UI_OT_reset_default_theme(wmOperatorType *ot)
360 {
361         /* identifiers */
362         ot->name = "Reset to Default Theme";
363         ot->idname = "UI_OT_reset_default_theme";
364         ot->description = "Reset to the default theme colors";
365         
366         /* callbacks */
367         ot->exec = reset_default_theme_exec;
368         
369         /* flags */
370         ot->flag = OPTYPE_REGISTER;
371 }
372
373 /* Copy Data Path Operator ------------------------ */
374
375 static int copy_data_path_button_poll(bContext *C)
376 {
377         PointerRNA ptr;
378         PropertyRNA *prop;
379         char *path;
380         int index;
381
382         uiContextActiveProperty(C, &ptr, &prop, &index);
383
384         if (ptr.id.data && ptr.data && prop) {
385                 path = RNA_path_from_ID_to_property(&ptr, prop);
386                 
387                 if (path) {
388                         MEM_freeN(path);
389                         return 1;
390                 }
391         }
392
393         return 0;
394 }
395
396 static int copy_data_path_button_exec(bContext *C, wmOperator *UNUSED(op))
397 {
398         PointerRNA ptr;
399         PropertyRNA *prop;
400         char *path;
401         int index;
402
403         /* try to create driver using property retrieved from UI */
404         uiContextActiveProperty(C, &ptr, &prop, &index);
405
406         if (ptr.id.data && ptr.data && prop) {
407                 path = RNA_path_from_ID_to_property(&ptr, prop);
408                 
409                 if (path) {
410                         WM_clipboard_text_set(path, FALSE);
411                         MEM_freeN(path);
412                         return OPERATOR_FINISHED;
413                 }
414         }
415
416         return OPERATOR_CANCELLED;
417 }
418
419 static void UI_OT_copy_data_path_button(wmOperatorType *ot)
420 {
421         /* identifiers */
422         ot->name = "Copy Data Path";
423         ot->idname = "UI_OT_copy_data_path_button";
424         ot->description = "Copy the RNA data path for this property to the clipboard";
425
426         /* callbacks */
427         ot->exec = copy_data_path_button_exec;
428         ot->poll = copy_data_path_button_poll;
429
430         /* flags */
431         ot->flag = OPTYPE_REGISTER;
432 }
433
434 /* Reset to Default Values Button Operator ------------------------ */
435
436 static int reset_default_button_poll(bContext *C)
437 {
438         PointerRNA ptr;
439         PropertyRNA *prop;
440         int index;
441
442         uiContextActiveProperty(C, &ptr, &prop, &index);
443         
444         return (ptr.data && prop && RNA_property_editable(&ptr, prop));
445 }
446
447 static int reset_default_button_exec(bContext *C, wmOperator *op)
448 {
449         PointerRNA ptr;
450         PropertyRNA *prop;
451         int success = 0;
452         int index, all = RNA_boolean_get(op->ptr, "all");
453
454         /* try to reset the nominated setting to its default value */
455         uiContextActiveProperty(C, &ptr, &prop, &index);
456         
457         /* if there is a valid property that is editable... */
458         if (ptr.data && prop && RNA_property_editable(&ptr, prop)) {
459                 if (RNA_property_reset(&ptr, prop, (all) ? -1 : index)) {
460                         /* perform updates required for this property */
461                         RNA_property_update(C, &ptr, prop);
462
463                         /* as if we pressed the button */
464                         uiContextActivePropertyHandle(C);
465
466                         success = 1;
467                 }
468         }
469
470         /* Since we don't want to undo _all_ edits to settings, eg window
471          * edits on the screen or on operator settings.
472          * it might be better to move undo's inline - campbell */
473         if (success) {
474                 ID *id = ptr.id.data;
475                 if (id && ID_CHECK_UNDO(id)) {
476                         /* do nothing, go ahead with undo */
477                 }
478                 else {
479                         return OPERATOR_CANCELLED;
480                 }
481         }
482         /* end hack */
483
484         return (success) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
485 }
486
487 static void UI_OT_reset_default_button(wmOperatorType *ot)
488 {
489         /* identifiers */
490         ot->name = "Reset to Default Value";
491         ot->idname = "UI_OT_reset_default_button";
492         ot->description = "Reset this property's value to its default value";
493
494         /* callbacks */
495         ot->poll = reset_default_button_poll;
496         ot->exec = reset_default_button_exec;
497
498         /* flags */
499         ot->flag = OPTYPE_UNDO;
500         
501         /* properties */
502         RNA_def_boolean(ot->srna, "all", 1, "All", "Reset to default values all elements of the array");
503 }
504
505 /* Copy To Selected Operator ------------------------ */
506
507 static int copy_to_selected_list(bContext *C, PointerRNA *ptr, ListBase *lb, int *use_path)
508 {
509         *use_path = FALSE;
510
511         if (RNA_struct_is_a(ptr->type, &RNA_EditBone))
512                 *lb = CTX_data_collection_get(C, "selected_editable_bones");
513         else if (RNA_struct_is_a(ptr->type, &RNA_PoseBone))
514                 *lb = CTX_data_collection_get(C, "selected_pose_bones");
515         else if (RNA_struct_is_a(ptr->type, &RNA_Sequence))
516                 *lb = CTX_data_collection_get(C, "selected_editable_sequences");
517         else {
518                 ID *id = ptr->id.data;
519
520                 if (id && GS(id->name) == ID_OB) {
521                         *lb = CTX_data_collection_get(C, "selected_editable_objects");
522                         *use_path = TRUE;
523                 }
524                 else
525                         return 0;
526         }
527         
528         return 1;
529 }
530
531 static int copy_to_selected_button_poll(bContext *C)
532 {
533         PointerRNA ptr, lptr, idptr;
534         PropertyRNA *prop, *lprop;
535         int index, success = 0;
536
537         uiContextActiveProperty(C, &ptr, &prop, &index);
538
539         if (ptr.data && prop) {
540                 char *path = NULL;
541                 int use_path;
542                 CollectionPointerLink *link;
543                 ListBase lb;
544
545                 if (!copy_to_selected_list(C, &ptr, &lb, &use_path))
546                         return success;
547
548                 if (!use_path || (path = RNA_path_from_ID_to_property(&ptr, prop))) {
549                         for (link = lb.first; link; link = link->next) {
550                                 if (link->ptr.data != ptr.data) {
551                                         if (use_path) {
552                                                 lprop = NULL;
553                                                 RNA_id_pointer_create(link->ptr.id.data, &idptr);
554                                                 RNA_path_resolve(&idptr, path, &lptr, &lprop);
555                                         }
556                                         else {
557                                                 lptr = link->ptr;
558                                                 lprop = prop;
559                                         }
560
561                                         if (lprop == prop) {
562                                                 if (RNA_property_editable(&lptr, prop))
563                                                         success = 1;
564                                         }
565                                 }
566                         }
567
568                         if (path)
569                                 MEM_freeN(path);
570                 }
571
572                 BLI_freelistN(&lb);
573         }
574
575         return success;
576 }
577
578 static int copy_to_selected_button_exec(bContext *C, wmOperator *op)
579 {
580         PointerRNA ptr, lptr, idptr;
581         PropertyRNA *prop, *lprop;
582         int success = 0;
583         int index, all = RNA_boolean_get(op->ptr, "all");
584
585         /* try to reset the nominated setting to its default value */
586         uiContextActiveProperty(C, &ptr, &prop, &index);
587         
588         /* if there is a valid property that is editable... */
589         if (ptr.data && prop) {
590                 char *path = NULL;
591                 int use_path;
592                 CollectionPointerLink *link;
593                 ListBase lb;
594
595                 if (!copy_to_selected_list(C, &ptr, &lb, &use_path))
596                         return success;
597
598                 if (!use_path || (path = RNA_path_from_ID_to_property(&ptr, prop))) {
599                         for (link = lb.first; link; link = link->next) {
600                                 if (link->ptr.data != ptr.data) {
601                                         if (use_path) {
602                                                 lprop = NULL;
603                                                 RNA_id_pointer_create(link->ptr.id.data, &idptr);
604                                                 RNA_path_resolve(&idptr, path, &lptr, &lprop);
605                                         }
606                                         else {
607                                                 lptr = link->ptr;
608                                                 lprop = prop;
609                                         }
610
611                                         if (lprop == prop) {
612                                                 if (RNA_property_editable(&lptr, lprop)) {
613                                                         if (RNA_property_copy(&lptr, &ptr, prop, (all) ? -1 : index)) {
614                                                                 RNA_property_update(C, &lptr, prop);
615                                                                 success = 1;
616                                                         }
617                                                 }
618                                         }
619                                 }
620                         }
621
622                         if (path)
623                                 MEM_freeN(path);
624                 }
625
626                 BLI_freelistN(&lb);
627         }
628         
629         return (success) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
630 }
631
632 static void UI_OT_copy_to_selected_button(wmOperatorType *ot)
633 {
634         /* identifiers */
635         ot->name = "Copy To Selected";
636         ot->idname = "UI_OT_copy_to_selected_button";
637         ot->description = "Copy property from this object to selected objects or bones";
638
639         /* callbacks */
640         ot->poll = copy_to_selected_button_poll;
641         ot->exec = copy_to_selected_button_exec;
642
643         /* flags */
644         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
645
646         /* properties */
647         RNA_def_boolean(ot->srna, "all", 1, "All", "Reset to default values all elements of the array");
648 }
649
650 /* Reports to Textblock Operator ------------------------ */
651
652 /* FIXME: this is just a temporary operator so that we can see all the reports somewhere 
653  * when there are too many to display...
654  */
655
656 static int reports_to_text_poll(bContext *C)
657 {
658         return CTX_wm_reports(C) != NULL;
659 }
660
661 static int reports_to_text_exec(bContext *C, wmOperator *UNUSED(op))
662 {
663         ReportList *reports = CTX_wm_reports(C);
664         Text *txt;
665         char *str;
666         
667         /* create new text-block to write to */
668         txt = BKE_text_add("Recent Reports");
669         
670         /* convert entire list to a display string, and add this to the text-block
671          *      - if commandline debug option enabled, show debug reports too
672          *      - otherwise, up to info (which is what users normally see)
673          */
674         str = BKE_reports_string(reports, (G.debug & G_DEBUG) ? RPT_DEBUG : RPT_INFO);
675
676         if (str) {
677                 BKE_text_write(txt, str);
678                 MEM_freeN(str);
679
680                 return OPERATOR_FINISHED;
681         }
682         else {
683                 return OPERATOR_CANCELLED;
684         }
685 }
686
687 static void UI_OT_reports_to_textblock(wmOperatorType *ot)
688 {
689         /* identifiers */
690         ot->name = "Reports to Text Block";
691         ot->idname = "UI_OT_reports_to_textblock";
692         ot->description = "Write the reports ";
693         
694         /* callbacks */
695         ot->poll = reports_to_text_poll;
696         ot->exec = reports_to_text_exec;
697 }
698
699 #ifdef WITH_PYTHON
700
701 /* ------------------------------------------------------------------------- */
702 /* EditSource Utility funcs and operator,
703  * note, this includes utility functions and button matching checks */
704
705 struct uiEditSourceStore {
706         uiBut but_orig;
707         GHash *hash;
708 } uiEditSourceStore;
709
710 struct uiEditSourceButStore {
711         char py_dbg_fn[FILE_MAX];
712         int py_dbg_ln;
713 } uiEditSourceButStore;
714
715 /* should only ever be set while the edit source operator is running */
716 static struct uiEditSourceStore *ui_editsource_info = NULL;
717
718 int  UI_editsource_enable_check(void)
719 {
720         return (ui_editsource_info != NULL);
721 }
722
723 static void ui_editsource_active_but_set(uiBut *but)
724 {
725         BLI_assert(ui_editsource_info == NULL);
726
727         ui_editsource_info = MEM_callocN(sizeof(uiEditSourceStore), __func__);
728         memcpy(&ui_editsource_info->but_orig, but, sizeof(uiBut));
729
730         ui_editsource_info->hash = BLI_ghash_ptr_new(__func__);
731 }
732
733 static void ui_editsource_active_but_clear(void)
734 {
735         BLI_ghash_free(ui_editsource_info->hash, NULL, (GHashValFreeFP)MEM_freeN);
736         MEM_freeN(ui_editsource_info);
737         ui_editsource_info = NULL;
738 }
739
740 static int ui_editsource_uibut_match(uiBut *but_a, uiBut *but_b)
741 {
742 #if 0
743         printf("matching buttons: '%s' == '%s'\n",
744                but_a->drawstr, but_b->drawstr);
745 #endif
746
747         /* this just needs to be a 'good-enough' comparison so we can know beyond
748          * reasonable doubt that these buttons are the same between redraws.
749          * if this fails it only means edit-source fails - campbell */
750         if (BLI_rctf_compare(&but_a->rect, &but_b->rect, FLT_EPSILON) &&
751             (but_a->type == but_b->type) &&
752             (but_a->rnaprop == but_b->rnaprop) &&
753             (but_a->optype == but_b->optype) &&
754             (but_a->unit_type == but_b->unit_type) &&
755             (strncmp(but_a->drawstr, but_b->drawstr, UI_MAX_DRAW_STR) == 0))
756         {
757                 return TRUE;
758         }
759         else {
760                 return FALSE;
761         }
762 }
763
764 void UI_editsource_active_but_test(uiBut *but)
765 {
766         extern void PyC_FileAndNum_Safe(const char **filename, int *lineno);
767
768         struct uiEditSourceButStore *but_store = MEM_callocN(sizeof(uiEditSourceButStore), __func__);
769
770         const char *fn;
771         int lineno = -1;
772
773 #if 0
774         printf("comparing buttons: '%s' == '%s'\n",
775                but->drawstr, ui_editsource_info->but_orig.drawstr);
776 #endif
777
778         PyC_FileAndNum_Safe(&fn, &lineno);
779
780         if (lineno != -1) {
781                 BLI_strncpy(but_store->py_dbg_fn, fn,
782                             sizeof(but_store->py_dbg_fn));
783                 but_store->py_dbg_ln = lineno;
784         }
785         else {
786                 but_store->py_dbg_fn[0] = '\0';
787                 but_store->py_dbg_ln = -1;
788         }
789
790         BLI_ghash_insert(ui_editsource_info->hash, but, but_store);
791 }
792
793 static int editsource_text_edit(bContext *C, wmOperator *op,
794                                 char filepath[FILE_MAX], int line)
795 {
796         struct Main *bmain = CTX_data_main(C);
797         Text *text;
798
799         for (text = bmain->text.first; text; text = text->id.next) {
800                 if (text->name && BLI_path_cmp(text->name, filepath) == 0) {
801                         break;
802                 }
803         }
804
805         if (text == NULL) {
806                 text = BKE_text_load(filepath, bmain->name);
807         }
808
809         if (text == NULL) {
810                 BKE_reportf(op->reports, RPT_WARNING, "File '%s' cannot be opened", filepath);
811                 return OPERATOR_CANCELLED;
812         }
813         else {
814                 /* naughty!, find text area to set, not good behavior
815                  * but since this is a dev tool lets allow it - campbell */
816                 ScrArea *sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_TEXT, 0);
817                 if (sa) {
818                         SpaceText *st = sa->spacedata.first;
819                         st->text = text;
820                 }
821                 else {
822                         BKE_reportf(op->reports, RPT_INFO, "See '%s' in the text editor", text->id.name + 2);
823                 }
824
825                 txt_move_toline(text, line - 1, FALSE);
826                 WM_event_add_notifier(C, NC_TEXT | ND_CURSOR, text);
827         }
828
829         return OPERATOR_FINISHED;
830 }
831
832 static int editsource_exec(bContext *C, wmOperator *op)
833 {
834         uiBut *but = uiContextActiveButton(C);
835
836         if (but) {
837                 GHashIterator ghi;
838                 struct uiEditSourceButStore *but_store = NULL;
839
840                 ARegion *ar = CTX_wm_region(C);
841                 int ret;
842
843                 /* needed else the active button does not get tested */
844                 uiFreeActiveButtons(C, CTX_wm_screen(C));
845
846                 // printf("%s: begin\n", __func__);
847
848                 /* take care not to return before calling ui_editsource_active_but_clear */
849                 ui_editsource_active_but_set(but);
850
851                 /* redraw and get active button python info */
852                 ED_region_do_draw(C, ar);
853
854                 for (BLI_ghashIterator_init(&ghi, ui_editsource_info->hash);
855                      !BLI_ghashIterator_isDone(&ghi);
856                      BLI_ghashIterator_step(&ghi))
857                 {
858                         uiBut *but_key = BLI_ghashIterator_getKey(&ghi);
859                         if (but_key && ui_editsource_uibut_match(&ui_editsource_info->but_orig, but_key)) {
860                                 but_store = BLI_ghashIterator_getValue(&ghi);
861                                 break;
862                         }
863
864                 }
865
866                 if (but_store) {
867                         if (but_store->py_dbg_ln != -1) {
868                                 ret = editsource_text_edit(C, op,
869                                                            but_store->py_dbg_fn,
870                                                            but_store->py_dbg_ln);
871                         }
872                         else {
873                                 BKE_report(op->reports, RPT_ERROR, "Active button is not from a script, cannot edit source");
874                                 ret = OPERATOR_CANCELLED;
875                         }
876                 }
877                 else {
878                         BKE_report(op->reports, RPT_ERROR, "Active button match cannot be found");
879                         ret = OPERATOR_CANCELLED;
880                 }
881
882
883                 ui_editsource_active_but_clear();
884
885                 // printf("%s: end\n", __func__);
886
887                 return ret;
888         }
889         else {
890                 BKE_report(op->reports, RPT_ERROR, "Active button not found");
891                 return OPERATOR_CANCELLED;
892         }
893 }
894
895 static void UI_OT_editsource(wmOperatorType *ot)
896 {
897         /* identifiers */
898         ot->name = "Edit Source";
899         ot->idname = "UI_OT_editsource";
900         ot->description = "Edit UI source code of the active button";
901
902         /* callbacks */
903         ot->exec = editsource_exec;
904 }
905
906 /* ------------------------------------------------------------------------- */
907 /* EditTranslation utility funcs and operator,
908  * Note: this includes utility functions and button matching checks.
909  *       this only works in conjunction with a py operator! */
910
911 static void edittranslation_find_po_file(const char *root, const char *uilng, char *path, const size_t maxlen)
912 {
913         char tstr[32]; /* Should be more than enough! */
914
915         /* First, full lang code. */
916         BLI_snprintf(tstr, sizeof(tstr), "%s.po", uilng);
917         BLI_join_dirfile(path, maxlen, root, uilng);
918         BLI_join_dirfile(path, maxlen, path, tstr);
919         if (BLI_is_file(path))
920                 return;
921
922         /* Now try without the second iso code part (_ES in es_ES). */
923         {
924                 char *tc = NULL;
925                 size_t szt = 0;
926                 tstr[0] = '\0';
927
928                 tc = strchr(uilng, '_');
929                 if (tc) {
930                         szt = tc - uilng;
931                         if (szt < sizeof(tstr)) /* Paranoid, should always be true! */
932                                 BLI_strncpy(tstr, uilng, szt + 1); /* +1 for '\0' char! */
933                 }
934                 if (tstr[0]) {
935                         /* Because of some codes like sr_SR@latin... */
936                         tc = strchr(uilng, '@');
937                         if (tc)
938                                 BLI_strncpy(tstr + szt, tc, sizeof(tstr) - szt);
939
940                         BLI_join_dirfile(path, maxlen, root, tstr);
941                         strcat(tstr, ".po");
942                         BLI_join_dirfile(path, maxlen, path, tstr);
943                         if (BLI_is_file(path))
944                                 return;
945                 }
946         }
947
948         /* Else no po file! */
949         path[0] = '\0';
950 }
951
952 static int edittranslation_exec(bContext *C, wmOperator *op)
953 {
954         uiBut *but = uiContextActiveButton(C);
955         int ret = OPERATOR_CANCELLED;
956
957         if (but) {
958                 PointerRNA ptr;
959                 char popath[FILE_MAX];
960                 const char *root = U.i18ndir;
961                 const char *uilng = BLF_lang_get();
962
963                 uiStringInfo but_label = {BUT_GET_LABEL, NULL};
964                 uiStringInfo rna_label = {BUT_GET_RNA_LABEL, NULL};
965                 uiStringInfo enum_label = {BUT_GET_RNAENUM_LABEL, NULL};
966                 uiStringInfo but_tip = {BUT_GET_TIP, NULL};
967                 uiStringInfo rna_tip = {BUT_GET_RNA_TIP, NULL};
968                 uiStringInfo enum_tip = {BUT_GET_RNAENUM_TIP, NULL};
969                 uiStringInfo rna_struct = {BUT_GET_RNASTRUCT_IDENTIFIER, NULL};
970                 uiStringInfo rna_prop = {BUT_GET_RNAPROP_IDENTIFIER, NULL};
971                 uiStringInfo rna_enum = {BUT_GET_RNAENUM_IDENTIFIER, NULL};
972                 uiStringInfo rna_ctxt = {BUT_GET_RNA_LABEL_CONTEXT, NULL};
973
974                 if (!BLI_is_dir(root)) {
975                         BKE_report(op->reports, RPT_ERROR, "Please set your User Preferences' 'Translation Branches "
976                                                            "Directory' path to a valid directory");
977                         return OPERATOR_CANCELLED;
978                 }
979                 if (!WM_operatortype_find(EDTSRC_I18N_OP_NAME, 0)) {
980                         BKE_reportf(op->reports, RPT_ERROR, "Could not find operator '%s'! Please enable ui_translate addon "
981                                                             "in the User Preferences", EDTSRC_I18N_OP_NAME);
982                         return OPERATOR_CANCELLED;
983                 }
984                 /* Try to find a valid po file for current language... */
985                 edittranslation_find_po_file(root, uilng, popath, FILE_MAX);
986 /*              printf("po path: %s\n", popath);*/
987                 if (popath[0] == '\0') {
988                         BKE_reportf(op->reports, RPT_ERROR, "No valid po found for language '%s' under %s", uilng, root);
989                         return OPERATOR_CANCELLED;
990                 }
991
992                 uiButGetStrInfo(C, but, &but_label, &rna_label, &enum_label, &but_tip, &rna_tip, &enum_tip,
993                                 &rna_struct, &rna_prop, &rna_enum, &rna_ctxt, NULL);
994
995                 WM_operator_properties_create(&ptr, EDTSRC_I18N_OP_NAME);
996                 RNA_string_set(&ptr, "lang", uilng);
997                 RNA_string_set(&ptr, "po_file", popath);
998                 RNA_string_set(&ptr, "but_label", but_label.strinfo);
999                 RNA_string_set(&ptr, "rna_label", rna_label.strinfo);
1000                 RNA_string_set(&ptr, "enum_label", enum_label.strinfo);
1001                 RNA_string_set(&ptr, "but_tip", but_tip.strinfo);
1002                 RNA_string_set(&ptr, "rna_tip", rna_tip.strinfo);
1003                 RNA_string_set(&ptr, "enum_tip", enum_tip.strinfo);
1004                 RNA_string_set(&ptr, "rna_struct", rna_struct.strinfo);
1005                 RNA_string_set(&ptr, "rna_prop", rna_prop.strinfo);
1006                 RNA_string_set(&ptr, "rna_enum", rna_enum.strinfo);
1007                 RNA_string_set(&ptr, "rna_ctxt", rna_ctxt.strinfo);
1008                 ret = WM_operator_name_call(C, EDTSRC_I18N_OP_NAME, WM_OP_INVOKE_DEFAULT, &ptr);
1009
1010                 /* Clean up */
1011                 if (but_label.strinfo)
1012                         MEM_freeN(but_label.strinfo);
1013                 if (rna_label.strinfo)
1014                         MEM_freeN(rna_label.strinfo);
1015                 if (enum_label.strinfo)
1016                         MEM_freeN(enum_label.strinfo);
1017                 if (but_tip.strinfo)
1018                         MEM_freeN(but_tip.strinfo);
1019                 if (rna_tip.strinfo)
1020                         MEM_freeN(rna_tip.strinfo);
1021                 if (enum_tip.strinfo)
1022                         MEM_freeN(enum_tip.strinfo);
1023                 if (rna_struct.strinfo)
1024                         MEM_freeN(rna_struct.strinfo);
1025                 if (rna_prop.strinfo)
1026                         MEM_freeN(rna_prop.strinfo);
1027                 if (rna_enum.strinfo)
1028                         MEM_freeN(rna_enum.strinfo);
1029                 if (rna_ctxt.strinfo)
1030                         MEM_freeN(rna_ctxt.strinfo);
1031
1032                 return ret;
1033         }
1034         else {
1035                 BKE_report(op->reports, RPT_ERROR, "Active button not found");
1036                 return OPERATOR_CANCELLED;
1037         }
1038 }
1039
1040 static void UI_OT_edittranslation_init(wmOperatorType *ot)
1041 {
1042         /* identifiers */
1043         ot->name = "Edit Translation";
1044         ot->idname = "UI_OT_edittranslation_init";
1045         ot->description = "Edit i18n in current language for the active button";
1046
1047         /* callbacks */
1048         ot->exec = edittranslation_exec;
1049 }
1050
1051 #endif /* WITH_PYTHON */
1052
1053 static int reloadtranslation_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1054 {
1055         BLF_lang_init();
1056         BLF_cache_clear();
1057         BLF_lang_set(NULL);
1058         UI_reinit_font();
1059         return OPERATOR_FINISHED;
1060 }
1061
1062 static void UI_OT_reloadtranslation(wmOperatorType *ot)
1063 {
1064         /* identifiers */
1065         ot->name = "Reload Translation";
1066         ot->idname = "UI_OT_reloadtranslation";
1067         ot->description = "Force a full reload of UI translation";
1068
1069         /* callbacks */
1070         ot->exec = reloadtranslation_exec;
1071 }
1072
1073 /* ********************************************************* */
1074 /* Registration */
1075
1076 void UI_buttons_operatortypes(void)
1077 {
1078         WM_operatortype_append(UI_OT_eyedropper);
1079         WM_operatortype_append(UI_OT_reset_default_theme);
1080         WM_operatortype_append(UI_OT_copy_data_path_button);
1081         WM_operatortype_append(UI_OT_reset_default_button);
1082         WM_operatortype_append(UI_OT_copy_to_selected_button);
1083         WM_operatortype_append(UI_OT_reports_to_textblock);  /* XXX: temp? */
1084
1085 #ifdef WITH_PYTHON
1086         WM_operatortype_append(UI_OT_editsource);
1087         WM_operatortype_append(UI_OT_edittranslation_init);
1088 #endif
1089         WM_operatortype_append(UI_OT_reloadtranslation);
1090 }
1091