Fix #34040: Moving Normal Node with enabled Cycles Material Preview crashes
[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         Main *bmain = CTX_data_main(C);
665         Text *txt;
666         char *str;
667         
668         /* create new text-block to write to */
669         txt = BKE_text_add(bmain, "Recent Reports");
670         
671         /* convert entire list to a display string, and add this to the text-block
672          *      - if commandline debug option enabled, show debug reports too
673          *      - otherwise, up to info (which is what users normally see)
674          */
675         str = BKE_reports_string(reports, (G.debug & G_DEBUG) ? RPT_DEBUG : RPT_INFO);
676
677         if (str) {
678                 BKE_text_write(txt, str);
679                 MEM_freeN(str);
680
681                 return OPERATOR_FINISHED;
682         }
683         else {
684                 return OPERATOR_CANCELLED;
685         }
686 }
687
688 static void UI_OT_reports_to_textblock(wmOperatorType *ot)
689 {
690         /* identifiers */
691         ot->name = "Reports to Text Block";
692         ot->idname = "UI_OT_reports_to_textblock";
693         ot->description = "Write the reports ";
694         
695         /* callbacks */
696         ot->poll = reports_to_text_poll;
697         ot->exec = reports_to_text_exec;
698 }
699
700 #ifdef WITH_PYTHON
701
702 /* ------------------------------------------------------------------------- */
703 /* EditSource Utility funcs and operator,
704  * note, this includes utility functions and button matching checks */
705
706 struct uiEditSourceStore {
707         uiBut but_orig;
708         GHash *hash;
709 } uiEditSourceStore;
710
711 struct uiEditSourceButStore {
712         char py_dbg_fn[FILE_MAX];
713         int py_dbg_ln;
714 } uiEditSourceButStore;
715
716 /* should only ever be set while the edit source operator is running */
717 static struct uiEditSourceStore *ui_editsource_info = NULL;
718
719 int  UI_editsource_enable_check(void)
720 {
721         return (ui_editsource_info != NULL);
722 }
723
724 static void ui_editsource_active_but_set(uiBut *but)
725 {
726         BLI_assert(ui_editsource_info == NULL);
727
728         ui_editsource_info = MEM_callocN(sizeof(uiEditSourceStore), __func__);
729         memcpy(&ui_editsource_info->but_orig, but, sizeof(uiBut));
730
731         ui_editsource_info->hash = BLI_ghash_ptr_new(__func__);
732 }
733
734 static void ui_editsource_active_but_clear(void)
735 {
736         BLI_ghash_free(ui_editsource_info->hash, NULL, (GHashValFreeFP)MEM_freeN);
737         MEM_freeN(ui_editsource_info);
738         ui_editsource_info = NULL;
739 }
740
741 static int ui_editsource_uibut_match(uiBut *but_a, uiBut *but_b)
742 {
743 #if 0
744         printf("matching buttons: '%s' == '%s'\n",
745                but_a->drawstr, but_b->drawstr);
746 #endif
747
748         /* this just needs to be a 'good-enough' comparison so we can know beyond
749          * reasonable doubt that these buttons are the same between redraws.
750          * if this fails it only means edit-source fails - campbell */
751         if (BLI_rctf_compare(&but_a->rect, &but_b->rect, FLT_EPSILON) &&
752             (but_a->type == but_b->type) &&
753             (but_a->rnaprop == but_b->rnaprop) &&
754             (but_a->optype == but_b->optype) &&
755             (but_a->unit_type == but_b->unit_type) &&
756             (strncmp(but_a->drawstr, but_b->drawstr, UI_MAX_DRAW_STR) == 0))
757         {
758                 return TRUE;
759         }
760         else {
761                 return FALSE;
762         }
763 }
764
765 void UI_editsource_active_but_test(uiBut *but)
766 {
767         extern void PyC_FileAndNum_Safe(const char **filename, int *lineno);
768
769         struct uiEditSourceButStore *but_store = MEM_callocN(sizeof(uiEditSourceButStore), __func__);
770
771         const char *fn;
772         int lineno = -1;
773
774 #if 0
775         printf("comparing buttons: '%s' == '%s'\n",
776                but->drawstr, ui_editsource_info->but_orig.drawstr);
777 #endif
778
779         PyC_FileAndNum_Safe(&fn, &lineno);
780
781         if (lineno != -1) {
782                 BLI_strncpy(but_store->py_dbg_fn, fn,
783                             sizeof(but_store->py_dbg_fn));
784                 but_store->py_dbg_ln = lineno;
785         }
786         else {
787                 but_store->py_dbg_fn[0] = '\0';
788                 but_store->py_dbg_ln = -1;
789         }
790
791         BLI_ghash_insert(ui_editsource_info->hash, but, but_store);
792 }
793
794 static int editsource_text_edit(bContext *C, wmOperator *op,
795                                 char filepath[FILE_MAX], int line)
796 {
797         struct Main *bmain = CTX_data_main(C);
798         Text *text;
799
800         for (text = bmain->text.first; text; text = text->id.next) {
801                 if (text->name && BLI_path_cmp(text->name, filepath) == 0) {
802                         break;
803                 }
804         }
805
806         if (text == NULL) {
807                 text = BKE_text_load(bmain, filepath, bmain->name);
808         }
809
810         if (text == NULL) {
811                 BKE_reportf(op->reports, RPT_WARNING, "File '%s' cannot be opened", filepath);
812                 return OPERATOR_CANCELLED;
813         }
814         else {
815                 /* naughty!, find text area to set, not good behavior
816                  * but since this is a dev tool lets allow it - campbell */
817                 ScrArea *sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_TEXT, 0);
818                 if (sa) {
819                         SpaceText *st = sa->spacedata.first;
820                         st->text = text;
821                 }
822                 else {
823                         BKE_reportf(op->reports, RPT_INFO, "See '%s' in the text editor", text->id.name + 2);
824                 }
825
826                 txt_move_toline(text, line - 1, FALSE);
827                 WM_event_add_notifier(C, NC_TEXT | ND_CURSOR, text);
828         }
829
830         return OPERATOR_FINISHED;
831 }
832
833 static int editsource_exec(bContext *C, wmOperator *op)
834 {
835         uiBut *but = uiContextActiveButton(C);
836
837         if (but) {
838                 GHashIterator ghi;
839                 struct uiEditSourceButStore *but_store = NULL;
840
841                 ARegion *ar = CTX_wm_region(C);
842                 int ret;
843
844                 /* needed else the active button does not get tested */
845                 uiFreeActiveButtons(C, CTX_wm_screen(C));
846
847                 // printf("%s: begin\n", __func__);
848
849                 /* take care not to return before calling ui_editsource_active_but_clear */
850                 ui_editsource_active_but_set(but);
851
852                 /* redraw and get active button python info */
853                 ED_region_do_draw(C, ar);
854
855                 for (BLI_ghashIterator_init(&ghi, ui_editsource_info->hash);
856                      !BLI_ghashIterator_isDone(&ghi);
857                      BLI_ghashIterator_step(&ghi))
858                 {
859                         uiBut *but_key = BLI_ghashIterator_getKey(&ghi);
860                         if (but_key && ui_editsource_uibut_match(&ui_editsource_info->but_orig, but_key)) {
861                                 but_store = BLI_ghashIterator_getValue(&ghi);
862                                 break;
863                         }
864
865                 }
866
867                 if (but_store) {
868                         if (but_store->py_dbg_ln != -1) {
869                                 ret = editsource_text_edit(C, op,
870                                                            but_store->py_dbg_fn,
871                                                            but_store->py_dbg_ln);
872                         }
873                         else {
874                                 BKE_report(op->reports, RPT_ERROR, "Active button is not from a script, cannot edit source");
875                                 ret = OPERATOR_CANCELLED;
876                         }
877                 }
878                 else {
879                         BKE_report(op->reports, RPT_ERROR, "Active button match cannot be found");
880                         ret = OPERATOR_CANCELLED;
881                 }
882
883
884                 ui_editsource_active_but_clear();
885
886                 // printf("%s: end\n", __func__);
887
888                 return ret;
889         }
890         else {
891                 BKE_report(op->reports, RPT_ERROR, "Active button not found");
892                 return OPERATOR_CANCELLED;
893         }
894 }
895
896 static void UI_OT_editsource(wmOperatorType *ot)
897 {
898         /* identifiers */
899         ot->name = "Edit Source";
900         ot->idname = "UI_OT_editsource";
901         ot->description = "Edit UI source code of the active button";
902
903         /* callbacks */
904         ot->exec = editsource_exec;
905 }
906
907 /* ------------------------------------------------------------------------- */
908 /* EditTranslation utility funcs and operator,
909  * Note: this includes utility functions and button matching checks.
910  *       this only works in conjunction with a py operator! */
911
912 static void edittranslation_find_po_file(const char *root, const char *uilng, char *path, const size_t maxlen)
913 {
914         char tstr[32]; /* Should be more than enough! */
915
916         /* First, full lang code. */
917         BLI_snprintf(tstr, sizeof(tstr), "%s.po", uilng);
918         BLI_join_dirfile(path, maxlen, root, uilng);
919         BLI_join_dirfile(path, maxlen, path, tstr);
920         if (BLI_is_file(path))
921                 return;
922
923         /* Now try without the second iso code part (_ES in es_ES). */
924         {
925                 char *tc = NULL;
926                 size_t szt = 0;
927                 tstr[0] = '\0';
928
929                 tc = strchr(uilng, '_');
930                 if (tc) {
931                         szt = tc - uilng;
932                         if (szt < sizeof(tstr)) /* Paranoid, should always be true! */
933                                 BLI_strncpy(tstr, uilng, szt + 1); /* +1 for '\0' char! */
934                 }
935                 if (tstr[0]) {
936                         /* Because of some codes like sr_SR@latin... */
937                         tc = strchr(uilng, '@');
938                         if (tc)
939                                 BLI_strncpy(tstr + szt, tc, sizeof(tstr) - szt);
940
941                         BLI_join_dirfile(path, maxlen, root, tstr);
942                         strcat(tstr, ".po");
943                         BLI_join_dirfile(path, maxlen, path, tstr);
944                         if (BLI_is_file(path))
945                                 return;
946                 }
947         }
948
949         /* Else no po file! */
950         path[0] = '\0';
951 }
952
953 static int edittranslation_exec(bContext *C, wmOperator *op)
954 {
955         uiBut *but = uiContextActiveButton(C);
956         int ret = OPERATOR_CANCELLED;
957
958         if (but) {
959                 PointerRNA ptr;
960                 char popath[FILE_MAX];
961                 const char *root = U.i18ndir;
962                 const char *uilng = BLF_lang_get();
963
964                 uiStringInfo but_label = {BUT_GET_LABEL, NULL};
965                 uiStringInfo rna_label = {BUT_GET_RNA_LABEL, NULL};
966                 uiStringInfo enum_label = {BUT_GET_RNAENUM_LABEL, NULL};
967                 uiStringInfo but_tip = {BUT_GET_TIP, NULL};
968                 uiStringInfo rna_tip = {BUT_GET_RNA_TIP, NULL};
969                 uiStringInfo enum_tip = {BUT_GET_RNAENUM_TIP, NULL};
970                 uiStringInfo rna_struct = {BUT_GET_RNASTRUCT_IDENTIFIER, NULL};
971                 uiStringInfo rna_prop = {BUT_GET_RNAPROP_IDENTIFIER, NULL};
972                 uiStringInfo rna_enum = {BUT_GET_RNAENUM_IDENTIFIER, NULL};
973                 uiStringInfo rna_ctxt = {BUT_GET_RNA_LABEL_CONTEXT, NULL};
974
975                 if (!BLI_is_dir(root)) {
976                         BKE_report(op->reports, RPT_ERROR, "Please set your User Preferences' 'Translation Branches "
977                                                            "Directory' path to a valid directory");
978                         return OPERATOR_CANCELLED;
979                 }
980                 if (!WM_operatortype_find(EDTSRC_I18N_OP_NAME, 0)) {
981                         BKE_reportf(op->reports, RPT_ERROR, "Could not find operator '%s'! Please enable ui_translate addon "
982                                                             "in the User Preferences", EDTSRC_I18N_OP_NAME);
983                         return OPERATOR_CANCELLED;
984                 }
985                 /* Try to find a valid po file for current language... */
986                 edittranslation_find_po_file(root, uilng, popath, FILE_MAX);
987 /*              printf("po path: %s\n", popath);*/
988                 if (popath[0] == '\0') {
989                         BKE_reportf(op->reports, RPT_ERROR, "No valid po found for language '%s' under %s", uilng, root);
990                         return OPERATOR_CANCELLED;
991                 }
992
993                 uiButGetStrInfo(C, but, &but_label, &rna_label, &enum_label, &but_tip, &rna_tip, &enum_tip,
994                                 &rna_struct, &rna_prop, &rna_enum, &rna_ctxt, NULL);
995
996                 WM_operator_properties_create(&ptr, EDTSRC_I18N_OP_NAME);
997                 RNA_string_set(&ptr, "lang", uilng);
998                 RNA_string_set(&ptr, "po_file", popath);
999                 RNA_string_set(&ptr, "but_label", but_label.strinfo);
1000                 RNA_string_set(&ptr, "rna_label", rna_label.strinfo);
1001                 RNA_string_set(&ptr, "enum_label", enum_label.strinfo);
1002                 RNA_string_set(&ptr, "but_tip", but_tip.strinfo);
1003                 RNA_string_set(&ptr, "rna_tip", rna_tip.strinfo);
1004                 RNA_string_set(&ptr, "enum_tip", enum_tip.strinfo);
1005                 RNA_string_set(&ptr, "rna_struct", rna_struct.strinfo);
1006                 RNA_string_set(&ptr, "rna_prop", rna_prop.strinfo);
1007                 RNA_string_set(&ptr, "rna_enum", rna_enum.strinfo);
1008                 RNA_string_set(&ptr, "rna_ctxt", rna_ctxt.strinfo);
1009                 ret = WM_operator_name_call(C, EDTSRC_I18N_OP_NAME, WM_OP_INVOKE_DEFAULT, &ptr);
1010
1011                 /* Clean up */
1012                 if (but_label.strinfo)
1013                         MEM_freeN(but_label.strinfo);
1014                 if (rna_label.strinfo)
1015                         MEM_freeN(rna_label.strinfo);
1016                 if (enum_label.strinfo)
1017                         MEM_freeN(enum_label.strinfo);
1018                 if (but_tip.strinfo)
1019                         MEM_freeN(but_tip.strinfo);
1020                 if (rna_tip.strinfo)
1021                         MEM_freeN(rna_tip.strinfo);
1022                 if (enum_tip.strinfo)
1023                         MEM_freeN(enum_tip.strinfo);
1024                 if (rna_struct.strinfo)
1025                         MEM_freeN(rna_struct.strinfo);
1026                 if (rna_prop.strinfo)
1027                         MEM_freeN(rna_prop.strinfo);
1028                 if (rna_enum.strinfo)
1029                         MEM_freeN(rna_enum.strinfo);
1030                 if (rna_ctxt.strinfo)
1031                         MEM_freeN(rna_ctxt.strinfo);
1032
1033                 return ret;
1034         }
1035         else {
1036                 BKE_report(op->reports, RPT_ERROR, "Active button not found");
1037                 return OPERATOR_CANCELLED;
1038         }
1039 }
1040
1041 static void UI_OT_edittranslation_init(wmOperatorType *ot)
1042 {
1043         /* identifiers */
1044         ot->name = "Edit Translation";
1045         ot->idname = "UI_OT_edittranslation_init";
1046         ot->description = "Edit i18n in current language for the active button";
1047
1048         /* callbacks */
1049         ot->exec = edittranslation_exec;
1050 }
1051
1052 #endif /* WITH_PYTHON */
1053
1054 static int reloadtranslation_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1055 {
1056         BLF_lang_init();
1057         BLF_cache_clear();
1058         BLF_lang_set(NULL);
1059         UI_reinit_font();
1060         return OPERATOR_FINISHED;
1061 }
1062
1063 static void UI_OT_reloadtranslation(wmOperatorType *ot)
1064 {
1065         /* identifiers */
1066         ot->name = "Reload Translation";
1067         ot->idname = "UI_OT_reloadtranslation";
1068         ot->description = "Force a full reload of UI translation";
1069
1070         /* callbacks */
1071         ot->exec = reloadtranslation_exec;
1072 }
1073
1074 /* ********************************************************* */
1075 /* Registration */
1076
1077 void UI_buttons_operatortypes(void)
1078 {
1079         WM_operatortype_append(UI_OT_eyedropper);
1080         WM_operatortype_append(UI_OT_reset_default_theme);
1081         WM_operatortype_append(UI_OT_copy_data_path_button);
1082         WM_operatortype_append(UI_OT_reset_default_button);
1083         WM_operatortype_append(UI_OT_copy_to_selected_button);
1084         WM_operatortype_append(UI_OT_reports_to_textblock);  /* XXX: temp? */
1085
1086 #ifdef WITH_PYTHON
1087         WM_operatortype_append(UI_OT_editsource);
1088         WM_operatortype_append(UI_OT_edittranslation_init);
1089 #endif
1090         WM_operatortype_append(UI_OT_reloadtranslation);
1091 }
1092