Cleanup
[blender.git] / source / blender / editors / interface / interface_handlers.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) 2008 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_handlers.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <assert.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_brush_types.h"
42 #include "DNA_sensor_types.h"
43 #include "DNA_controller_types.h"
44 #include "DNA_actuator_types.h"
45
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_screen_types.h"
49
50 #include "BLI_math.h"
51 #include "BLI_listbase.h"
52 #include "BLI_linklist.h"
53 #include "BLI_string.h"
54 #include "BLI_string_utf8.h"
55 #include "BLI_rect.h"
56 #include "BLI_utildefines.h"
57 #include "BLI_string_cursor_utf8.h"
58
59 #include "BLF_translation.h"
60
61 #include "PIL_time.h"
62
63 #include "BKE_blender.h"
64 #include "BKE_brush.h"
65 #include "BKE_colortools.h"
66 #include "BKE_context.h"
67 #include "BKE_idprop.h"
68 #include "BKE_report.h"
69 #include "BKE_screen.h"
70 #include "BKE_texture.h"
71 #include "BKE_tracking.h"
72 #include "BKE_unit.h"
73 #include "BKE_paint.h"
74
75 #include "ED_screen.h"
76 #include "ED_util.h"
77 #include "ED_keyframing.h"
78
79 #include "UI_interface.h"
80
81 #include "BLF_api.h"
82
83 #include "interface_intern.h"
84
85 #include "RNA_access.h"
86
87 #include "WM_api.h"
88 #include "WM_types.h"
89
90 /* place the mouse at the scaled down location when un-grabbing */
91 #define USE_CONT_MOUSE_CORRECT
92 /* support dragging toggle buttons */
93 #define USE_DRAG_TOGGLE
94
95 /* support dragging multiple number buttons at once */
96 #define USE_DRAG_MULTINUM
97
98 /* so we can avoid very small mouse-moves from jumping away from keyboard navigation [#34936] */
99 #define USE_KEYNAV_LIMIT
100
101 /* drag popups by their header */
102 #define USE_DRAG_POPUP
103
104 /* proto */
105 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to);
106 static void ui_add_link(bContext *C, uiBut *from, uiBut *to);
107 static int ui_do_but_EXIT(bContext *C, uiBut *but, struct uiHandleButtonData *data, const wmEvent *event);
108
109 #ifdef USE_KEYNAV_LIMIT
110 static void ui_mouse_motion_keynav_init(struct uiKeyNavLock *keynav, const wmEvent *event);
111 static bool ui_mouse_motion_keynav_test(struct uiKeyNavLock *keynav, const wmEvent *event);
112 #endif
113
114 /***************** structs and defines ****************/
115
116 #define BUTTON_TOOLTIP_DELAY        0.500
117 #define BUTTON_FLASH_DELAY          0.020
118 #define MENU_SCROLL_INTERVAL        0.1
119 #define BUTTON_AUTO_OPEN_THRESH     0.3
120 #define BUTTON_MOUSE_TOWARDS_THRESH 1.0
121 /* pixels to move the cursor to get out of keyboard navigation */
122 #define BUTTON_KEYNAV_PX_LIMIT      8
123
124 #define MENU_TOWARDS_MARGIN 20  /* margin in pixels */
125 #define MENU_TOWARDS_WIGGLE_ROOM 64  /* tolerance in pixels */
126
127 typedef enum uiButtonActivateType {
128         BUTTON_ACTIVATE_OVER,
129         BUTTON_ACTIVATE,
130         BUTTON_ACTIVATE_APPLY,
131         BUTTON_ACTIVATE_TEXT_EDITING,
132         BUTTON_ACTIVATE_OPEN
133 } uiButtonActivateType;
134
135 typedef enum uiHandleButtonState {
136         BUTTON_STATE_INIT,
137         BUTTON_STATE_HIGHLIGHT,
138         BUTTON_STATE_WAIT_FLASH,
139         BUTTON_STATE_WAIT_RELEASE,
140         BUTTON_STATE_WAIT_KEY_EVENT,
141         BUTTON_STATE_NUM_EDITING,
142         BUTTON_STATE_TEXT_EDITING,
143         BUTTON_STATE_TEXT_SELECTING,
144         BUTTON_STATE_MENU_OPEN,
145         BUTTON_STATE_WAIT_DRAG,
146         BUTTON_STATE_EXIT
147 } uiHandleButtonState;
148
149
150 #ifdef USE_DRAG_MULTINUM
151
152 /* how far to drag before we check for gesture direction (in pixels),
153  * note: half the height of a button is about right... */
154 #define DRAG_MULTINUM_THRESHOLD_DRAG_X (UI_UNIT_Y / 4)
155
156 /* how far to drag horizontally before we stop checkign which buttons the gesture spans (in pixels),
157  * locking down the buttons so we can drag freely without worrying about vertical movement. */
158 #define DRAG_MULTINUM_THRESHOLD_DRAG_Y (UI_UNIT_Y / 4)
159
160 /* how strict to be when detecting a vertical gesture, [0.5 == sloppy], [0.9 == strict], (unsigned dot-product)
161  * note: we should be quite strict here, since doing a vertical gesture by accident should be avoided,
162  * however with some care a user should be able to do a vertical movement without *missing*. */
163 #define DRAG_MULTINUM_THRESHOLD_VERTICAL (0.75f)
164
165
166 /* a simple version of uiHandleButtonData when accessing multiple buttons */
167 typedef struct uiButMultiState {
168         double origvalue;
169         uiBut *but;
170 } uiButMultiState;
171
172 typedef struct uiHandleButtonMulti {
173         enum {
174                 BUTTON_MULTI_INIT_UNSET = 0,    /* gesture direction unknown, wait until mouse has moved enough... */
175                 BUTTON_MULTI_INIT_SETUP,        /* vertical gesture detected, flag buttons interactively (UI_BUT_DRAG_MULTI) */
176                 BUTTON_MULTI_INIT_ENABLE,       /* flag buttons finished, apply horizontal motion to active and flagged */
177                 BUTTON_MULTI_INIT_DISABLE,      /* vertical gesture _not_ detected, take no further action */
178         } init;
179
180         bool has_mbuts;  /* any buttons flagged UI_BUT_DRAG_MULTI */
181         LinkNode *mbuts;
182         uiButStore *bs_mbuts;
183
184         bool is_proportional;
185
186         /* before activating, we need to check gesture direction
187          * accumulate signed cursor movement here so we can tell if this is a vertical motion or not. */
188         float drag_dir[2];
189
190         /* values copied direct from event->x,y
191          * used to detect buttons between the current and initial mouse position */
192         int drag_start[2];
193
194         /* store x location once BUTTON_MULTI_INIT_SETUP is set,
195          * moving outside this sets BUTTON_MULTI_INIT_ENABLE */
196         int drag_lock_x;
197
198 } uiHandleButtonMulti;
199
200 #endif  /* USE_DRAG_MULTINUM */
201
202
203
204 typedef struct uiHandleButtonData {
205         wmWindowManager *wm;
206         wmWindow *window;
207         ARegion *region;
208
209         bool interactive;
210
211         /* overall state */
212         uiHandleButtonState state;
213         int retval;
214         /* booleans (could be made into flags) */
215         bool cancel, escapecancel;
216         bool applied, applied_interactive;
217         wmTimer *flashtimer;
218
219         /* edited value */
220         char *str, *origstr;
221         double value, origvalue, startvalue;
222         float vec[3], origvec[3];
223 #if 0  /* UNUSED */
224         int togdual, togonly;
225 #endif
226         ColorBand *coba;
227
228         /* tooltip */
229         ARegion *tooltip;
230         wmTimer *tooltiptimer;
231         
232         /* auto open */
233         bool used_mouse;
234         wmTimer *autoopentimer;
235
236         /* text selection/editing */
237         int maxlen, selextend;
238         float selstartx;
239
240         /* number editing / dragging */
241         /* coords are Window/uiBlock relative (depends on the button) */
242         int draglastx, draglasty;
243         int dragstartx, dragstarty;
244         int draglastvalue;
245         int dragstartvalue;
246         bool dragchange, draglock;
247         int dragsel;
248         float dragf, dragfstart;
249         CBData *dragcbd;
250
251 #ifdef USE_CONT_MOUSE_CORRECT
252         /* when ungrabbing buttons which are #ui_is_a_warp_but(), we may want to position them
253          * FLT_MAX signifies do-nothing, use #ui_block_to_window_fl() to get this into a usable space  */
254         float ungrab_mval[2];
255 #endif
256
257         /* menu open (watch uiFreeActiveButtons) */
258         uiPopupBlockHandle *menu;
259         int menuretval;
260         
261         /* search box (watch uiFreeActiveButtons) */
262         ARegion *searchbox;
263 #ifdef USE_KEYNAV_LIMIT
264         struct uiKeyNavLock searchbox_keynav_state;
265 #endif
266
267 #ifdef USE_DRAG_MULTINUM
268         /* Multi-buttons will be updated in unison with the active button. */
269         uiHandleButtonMulti multi_data;
270 #endif
271
272         /* post activate */
273         uiButtonActivateType posttype;
274         uiBut *postbut;
275 } uiHandleButtonData;
276
277 typedef struct uiAfterFunc {
278         struct uiAfterFunc *next, *prev;
279
280         uiButHandleFunc func;
281         void *func_arg1;
282         void *func_arg2;
283         
284         uiButHandleNFunc funcN;
285         void *func_argN;
286
287         uiButHandleRenameFunc rename_func;
288         void *rename_arg1;
289         void *rename_orig;
290         
291         uiBlockHandleFunc handle_func;
292         void *handle_func_arg;
293         int retval;
294
295         uiMenuHandleFunc butm_func;
296         void *butm_func_arg;
297         int a2;
298
299         wmOperatorType *optype;
300         int opcontext;
301         PointerRNA *opptr;
302
303         PointerRNA rnapoin;
304         PropertyRNA *rnaprop;
305
306         bContextStore *context;
307
308         char undostr[BKE_UNDO_STR_MAX];
309 } uiAfterFunc;
310
311
312
313 static bool ui_is_but_interactive(const uiBut *but, const bool labeledit);
314 static bool ui_but_contains_pt(uiBut *but, float mx, float my);
315 static bool ui_mouse_inside_button(ARegion *ar, uiBut *but, int x, int y);
316 static uiBut *ui_but_find_mouse_over_ex(ARegion *ar, const int x, const int y, const bool labeledit);
317 static uiBut *ui_but_find_mouse_over(ARegion *ar, const wmEvent *event);
318 static void button_activate_init(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
319 static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState state);
320 static void button_activate_exit(bContext *C, uiBut *but, uiHandleButtonData *data,
321                                  const bool mousemove, const bool onfree);
322 static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *userdata);
323 static void ui_handle_button_activate(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
324 static void button_timers_tooltip_remove(bContext *C, uiBut *but);
325
326 #ifdef USE_DRAG_MULTINUM
327 static void ui_multibut_restore(uiHandleButtonData *data, uiBlock *block);
328 static uiButMultiState *ui_multibut_lookup(uiHandleButtonData *data, const uiBut *but);
329 #endif
330
331 /* buttons clipboard */
332 static ColorBand but_copypaste_coba = {0};
333 static CurveMapping but_copypaste_curve = {0};
334 static bool but_copypaste_curve_alive = false;
335
336 /* ******************** menu navigation helpers ************** */
337 enum eSnapType {
338         SNAP_OFF = 0,
339         SNAP_ON,
340         SNAP_ON_SMALL,
341 };
342
343 static enum eSnapType ui_event_to_snap(const wmEvent *event)
344 {
345         return (event->ctrl) ? (event->shift) ? SNAP_ON_SMALL : SNAP_ON : SNAP_OFF;
346 }
347
348 static void ui_color_snap_hue(const enum eSnapType snap, float *r_hue)
349 {
350         const float snap_increment = (snap == SNAP_ON_SMALL) ? 24 : 12;
351         BLI_assert(snap != SNAP_OFF);
352         *r_hue = floorf(0.5f + ((*r_hue) * snap_increment)) / snap_increment;
353 }
354
355 /* assumes event type is MOUSEPAN */
356 void ui_pan_to_scroll(const wmEvent *event, int *type, int *val)
357 {
358         static int lastdy = 0;
359         int dy = event->prevy - event->y;
360
361         /* This event should be originally from event->type,
362          * converting wrong event into wheel is bad, see [#33803] */
363         BLI_assert(*type == MOUSEPAN);
364
365         /* sign differs, reset */
366         if ((dy > 0 && lastdy < 0) || (dy < 0 && lastdy > 0)) {
367                 lastdy = dy;
368         }
369         else {
370                 lastdy += dy;
371                 
372                 if (ABS(lastdy) > (int)UI_UNIT_Y) {
373                         if (U.uiflag2 & USER_TRACKPAD_NATURAL)
374                                 dy = -dy;
375                         
376                         *val = KM_PRESS;
377                         
378                         if (dy > 0)
379                                 *type = WHEELUPMOUSE;
380                         else
381                                 *type = WHEELDOWNMOUSE;
382                         
383                         lastdy = 0;
384                 }
385         }
386 }
387
388 static bool ui_but_editable(uiBut *but)
389 {
390         return ELEM(but->type, LABEL, SEPR, SEPRLINE, ROUNDBOX, LISTBOX, PROGRESSBAR);
391 }
392
393 static uiBut *ui_but_prev(uiBut *but)
394 {
395         while (but->prev) {
396                 but = but->prev;
397                 if (!ui_but_editable(but)) return but;
398         }
399         return NULL;
400 }
401
402 static uiBut *ui_but_next(uiBut *but)
403 {
404         while (but->next) {
405                 but = but->next;
406                 if (!ui_but_editable(but)) return but;
407         }
408         return NULL;
409 }
410
411 static uiBut *ui_but_first(uiBlock *block)
412 {
413         uiBut *but;
414         
415         but = block->buttons.first;
416         while (but) {
417                 if (!ui_but_editable(but)) return but;
418                 but = but->next;
419         }
420         return NULL;
421 }
422
423 static uiBut *ui_but_last(uiBlock *block)
424 {
425         uiBut *but;
426         
427         but = block->buttons.last;
428         while (but) {
429                 if (!ui_but_editable(but)) return but;
430                 but = but->prev;
431         }
432         return NULL;
433 }
434
435 static bool ui_is_a_warp_but(uiBut *but)
436 {
437         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
438                 if (ELEM(but->type, NUM, NUMSLI, HSVCIRCLE, TRACKPREVIEW, HSVCUBE, BUT_CURVE)) {
439                         return true;
440                 }
441         }
442
443         return false;
444 }
445
446 static float ui_mouse_scale_warp_factor(const bool shift)
447 {
448         return shift ? 0.05f : 1.0f;
449 }
450
451 static void ui_mouse_scale_warp(uiHandleButtonData *data,
452                                 const float mx, const float my,
453                                 float *r_mx, float *r_my,
454                                 const bool shift)
455 {
456         const float fac = ui_mouse_scale_warp_factor(shift);
457         
458         /* slow down the mouse, this is fairly picky */
459         *r_mx = (data->dragstartx * (1.0f - fac) + mx * fac);
460         *r_my = (data->dragstarty * (1.0f - fac) + my * fac);
461 }
462
463 /* file selectors are exempt from utf-8 checks */
464 bool ui_is_but_utf8(const uiBut *but)
465 {
466         if (but->rnaprop) {
467                 const int subtype = RNA_property_subtype(but->rnaprop);
468                 return !(ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME, PROP_BYTESTRING));
469         }
470         else {
471                 return !(but->flag & UI_BUT_NO_UTF8);
472         }
473 }
474
475 /* ********************** button apply/revert ************************/
476
477 static ListBase UIAfterFuncs = {NULL, NULL};
478
479 static uiAfterFunc *ui_afterfunc_new(void)
480 {
481         uiAfterFunc *after;
482
483         after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
484
485         BLI_addtail(&UIAfterFuncs, after);
486
487         return after;
488 }
489
490 /**
491  * For executing operators after the button is pressed.
492  * (some non operator buttons need to trigger operators), see: [#37795]
493  *
494  * \note Can only call while handling buttons.
495  */
496 PointerRNA *ui_handle_afterfunc_add_operator(wmOperatorType *ot, int opcontext, bool create_props)
497 {
498         PointerRNA *ptr = NULL;
499         uiAfterFunc *after = ui_afterfunc_new();
500
501         after->optype = ot;
502         after->opcontext = opcontext;
503
504         if (create_props) {
505                 ptr = MEM_callocN(sizeof(PointerRNA), __func__);
506                 WM_operator_properties_create_ptr(ptr, ot);
507                 after->opptr = ptr;
508         }
509
510         return ptr;
511 }
512
513 static void ui_apply_but_func(bContext *C, uiBut *but)
514 {
515         uiAfterFunc *after;
516         uiBlock *block = but->block;
517
518         /* these functions are postponed and only executed after all other
519          * handling is done, i.e. menus are closed, in order to avoid conflicts
520          * with these functions removing the buttons we are working with */
521
522         if (but->func || but->funcN || block->handle_func || but->rename_func ||
523             (but->type == BUTM && block->butm_func) || but->optype || but->rnaprop)
524         {
525                 after = ui_afterfunc_new();
526
527                 if (but->func && ELEM(but, but->func_arg1, but->func_arg2)) {
528                         /* exception, this will crash due to removed button otherwise */
529                         but->func(C, but->func_arg1, but->func_arg2);
530                 }
531                 else
532                         after->func = but->func;
533
534                 after->func_arg1 = but->func_arg1;
535                 after->func_arg2 = but->func_arg2;
536
537                 after->funcN = but->funcN;
538                 after->func_argN = (but->func_argN) ? MEM_dupallocN(but->func_argN) : NULL;
539
540                 after->rename_func = but->rename_func;
541                 after->rename_arg1 = but->rename_arg1;
542                 after->rename_orig = but->rename_orig; /* needs free! */
543
544                 after->handle_func = block->handle_func;
545                 after->handle_func_arg = block->handle_func_arg;
546                 after->retval = but->retval;
547
548                 if (but->type == BUTM) {
549                         after->butm_func = block->butm_func;
550                         after->butm_func_arg = block->butm_func_arg;
551                         after->a2 = but->a2;
552                 }
553
554                 after->optype = but->optype;
555                 after->opcontext = but->opcontext;
556                 after->opptr = but->opptr;
557
558                 after->rnapoin = but->rnapoin;
559                 after->rnaprop = but->rnaprop;
560
561                 if (but->context)
562                         after->context = CTX_store_copy(but->context);
563
564                 but->optype = NULL;
565                 but->opcontext = 0;
566                 but->opptr = NULL;
567         }
568 }
569
570 /* typically call ui_apply_undo(), ui_apply_autokey() */
571 static void ui_apply_undo(uiBut *but)
572 {
573         uiAfterFunc *after;
574
575         if (but->flag & UI_BUT_UNDO) {
576                 const char *str = NULL;
577
578                 /* define which string to use for undo */
579                 if (ELEM(but->type, LINK, INLINK)) str = "Add button link";
580                 else if (but->type == MENU) str = but->drawstr;
581                 else if (but->drawstr[0]) str = but->drawstr;
582                 else str = but->tip;
583
584                 /* fallback, else we don't get an undo! */
585                 if (str == NULL || str[0] == '\0') {
586                         str = "Unknown Action";
587                 }
588
589                 /* delayed, after all other funcs run, popups are closed, etc */
590                 after = ui_afterfunc_new();
591                 BLI_strncpy(after->undostr, str, sizeof(after->undostr));
592         }
593 }
594
595 static void ui_apply_autokey(bContext *C, uiBut *but)
596 {
597         Scene *scene = CTX_data_scene(C);
598
599         /* try autokey */
600         ui_but_anim_autokey(C, but, scene, scene->r.cfra);
601
602         /* make a little report about what we've done! */
603         if (but->rnaprop) {
604                 char *buf = WM_prop_pystring_assign(C, &but->rnapoin, but->rnaprop, but->rnaindex);
605                 if (buf) {
606                         BKE_report(CTX_wm_reports(C), RPT_PROPERTY, buf);
607                         MEM_freeN(buf);
608
609                         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
610                 }
611         }
612 }
613
614 static void ui_apply_but_funcs_after(bContext *C)
615 {
616         uiAfterFunc *afterf, after;
617         PointerRNA opptr;
618         ListBase funcs;
619
620         /* copy to avoid recursive calls */
621         funcs = UIAfterFuncs;
622         BLI_listbase_clear(&UIAfterFuncs);
623
624         for (afterf = funcs.first; afterf; afterf = after.next) {
625                 after = *afterf; /* copy to avoid memleak on exit() */
626                 BLI_freelinkN(&funcs, afterf);
627
628                 if (after.context)
629                         CTX_store_set(C, after.context);
630
631                 if (after.opptr) {
632                         /* free in advance to avoid leak on exit */
633                         opptr = *after.opptr,
634                         MEM_freeN(after.opptr);
635                 }
636
637                 if (after.optype)
638                         WM_operator_name_call_ptr(C, after.optype, after.opcontext, (after.opptr) ? &opptr : NULL);
639
640                 if (after.opptr)
641                         WM_operator_properties_free(&opptr);
642
643                 if (after.rnapoin.data)
644                         RNA_property_update(C, &after.rnapoin, after.rnaprop);
645
646                 if (after.context) {
647                         CTX_store_set(C, NULL);
648                         CTX_store_free(after.context);
649                 }
650
651                 if (after.func)
652                         after.func(C, after.func_arg1, after.func_arg2);
653                 if (after.funcN)
654                         after.funcN(C, after.func_argN, after.func_arg2);
655                 if (after.func_argN)
656                         MEM_freeN(after.func_argN);
657                 
658                 if (after.handle_func)
659                         after.handle_func(C, after.handle_func_arg, after.retval);
660                 if (after.butm_func)
661                         after.butm_func(C, after.butm_func_arg, after.a2);
662                 
663                 if (after.rename_func)
664                         after.rename_func(C, after.rename_arg1, after.rename_orig);
665                 if (after.rename_orig)
666                         MEM_freeN(after.rename_orig);
667                 
668                 if (after.undostr[0])
669                         ED_undo_push(C, after.undostr);
670         }
671 }
672
673 static void ui_apply_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data)
674 {
675         ui_apply_but_func(C, but);
676
677         data->retval = but->retval;
678         data->applied = true;
679 }
680
681 static void ui_apply_but_BUTM(bContext *C, uiBut *but, uiHandleButtonData *data)
682 {
683         ui_set_but_val(but, but->hardmin);
684         ui_apply_but_func(C, but);
685
686         data->retval = but->retval;
687         data->applied = true;
688 }
689
690 static void ui_apply_but_BLOCK(bContext *C, uiBut *but, uiHandleButtonData *data)
691 {
692         if (but->type == MENU)
693                 ui_set_but_val(but, data->value);
694
695         ui_check_but(but);
696         ui_apply_but_func(C, but);
697         data->retval = but->retval;
698         data->applied = true;
699 }
700
701 static void ui_apply_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data)
702 {
703         double value;
704         int w, lvalue, push;
705         
706         value = ui_get_but_val(but);
707         lvalue = (int)value;
708         
709         if (but->bit) {
710                 w = UI_BITBUT_TEST(lvalue, but->bitnr);
711                 if (w) lvalue = UI_BITBUT_CLR(lvalue, but->bitnr);
712                 else   lvalue = UI_BITBUT_SET(lvalue, but->bitnr);
713                 
714                 ui_set_but_val(but, (double)lvalue);
715                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
716         }
717         else {
718                 
719                 if (value == 0.0) push = 1;
720                 else push = 0;
721                 
722                 if (ELEM(but->type, TOGN, ICONTOGN, OPTIONN)) push = !push;
723                 ui_set_but_val(but, (double)push);
724                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
725         }
726         
727         ui_apply_but_func(C, but);
728
729         data->retval = but->retval;
730         data->applied = true;
731 }
732
733 static void ui_apply_but_ROW(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
734 {
735         uiBut *bt;
736
737         ui_set_but_val(but, but->hardmax);
738
739         ui_apply_but_func(C, but);
740
741         /* states of other row buttons */
742         for (bt = block->buttons.first; bt; bt = bt->next)
743                 if (bt != but && bt->poin == but->poin && ELEM(bt->type, ROW, LISTROW))
744                         ui_check_but(bt);
745
746         data->retval = but->retval;
747         data->applied = true;
748 }
749
750 static void ui_apply_but_TEX(bContext *C, uiBut *but, uiHandleButtonData *data)
751 {
752         if (!data->str)
753                 return;
754
755         ui_set_but_string(C, but, data->str);
756         ui_check_but(but);
757
758         /* give butfunc the original text too */
759         /* feature used for bone renaming, channels, etc */
760         /* afterfunc frees origstr */
761         but->rename_orig = data->origstr;
762         data->origstr = NULL;
763         ui_apply_but_func(C, but);
764
765         data->retval = but->retval;
766         data->applied = true;
767 }
768
769 static void ui_apply_but_NUM(bContext *C, uiBut *but, uiHandleButtonData *data)
770 {
771         if (data->str) {
772                 if (ui_set_but_string(C, but, data->str)) {
773                         data->value = ui_get_but_val(but);
774                 }
775                 else {
776                         data->cancel = true;
777                         return;
778                 }
779         }
780         else
781                 ui_set_but_val(but, data->value);
782
783         ui_check_but(but);
784         ui_apply_but_func(C, but);
785
786         data->retval = but->retval;
787         data->applied = true;
788 }
789
790 static void ui_apply_but_VEC(bContext *C, uiBut *but, uiHandleButtonData *data)
791 {
792         ui_set_but_vectorf(but, data->vec);
793         ui_check_but(but);
794         ui_apply_but_func(C, but);
795
796         data->retval = but->retval;
797         data->applied = true;
798 }
799
800 static void ui_apply_but_COLORBAND(bContext *C, uiBut *but, uiHandleButtonData *data)
801 {
802         ui_apply_but_func(C, but);
803         data->retval = but->retval;
804         data->applied = true;
805 }
806
807 static void ui_apply_but_CURVE(bContext *C, uiBut *but, uiHandleButtonData *data)
808 {
809         ui_apply_but_func(C, but);
810         data->retval = but->retval;
811         data->applied = true;
812 }
813
814 /* ****************** drag drop code *********************** */
815
816
817 #ifdef USE_DRAG_MULTINUM
818
819 /* small multi-but api */
820 static void ui_multibut_add(uiHandleButtonData *data, uiBut *but)
821 {
822         uiButMultiState *mbut_state;
823
824         BLI_assert(but->flag & UI_BUT_DRAG_MULTI);
825         BLI_assert(data->multi_data.has_mbuts);
826
827
828         mbut_state = MEM_callocN(sizeof(*mbut_state), __func__);
829         mbut_state->but = but;
830         mbut_state->origvalue = ui_get_but_val(but);
831
832         BLI_linklist_prepend(&data->multi_data.mbuts, mbut_state);
833
834         UI_butstore_register(data->multi_data.bs_mbuts, &mbut_state->but);
835 }
836
837 static uiButMultiState *ui_multibut_lookup(uiHandleButtonData *data, const uiBut *but)
838 {
839         LinkNode *l;
840
841         for (l = data->multi_data.mbuts; l; l = l->next) {
842                 uiButMultiState *mbut_state;
843
844                 mbut_state = l->link;
845
846                 if (mbut_state->but == but) {
847                         return mbut_state;
848                 }
849         }
850
851         return NULL;
852 }
853
854 static void ui_multibut_restore(uiHandleButtonData *data, uiBlock *block)
855 {
856         uiBut *but;
857
858         for (but = block->buttons.first; but; but = but->next) {
859                 if (but->flag & UI_BUT_DRAG_MULTI) {
860                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
861                         if (mbut_state) {
862                                 ui_set_but_val(but, mbut_state->origvalue);
863                         }
864                 }
865         }
866 }
867
868 static void ui_multibut_free(uiHandleButtonData *data, uiBlock *block)
869 {
870         BLI_linklist_freeN(data->multi_data.mbuts);
871         data->multi_data.mbuts = NULL;
872
873         if (data->multi_data.bs_mbuts) {
874                 UI_butstore_free(block, data->multi_data.bs_mbuts);
875                 data->multi_data.bs_mbuts = NULL;
876         }
877 }
878
879 static bool ui_multibut_states_tag(uiBut *but_active, uiHandleButtonData *data, const wmEvent *event)
880 {
881         uiBut *but;
882         float seg[2][2];
883         bool changed = false;
884
885         seg[0][0] = data->multi_data.drag_start[0];
886         seg[0][1] = data->multi_data.drag_start[1];
887
888         seg[1][0] = event->x;
889         seg[1][1] = event->y;
890
891         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
892
893         ui_window_to_block_fl(data->region, but_active->block, &seg[0][0], &seg[0][1]);
894         ui_window_to_block_fl(data->region, but_active->block, &seg[1][0], &seg[1][1]);
895
896         data->multi_data.has_mbuts = false;
897
898         /* follow ui_but_find_mouse_over_ex logic */
899         for (but = but_active->block->buttons.first; but; but = but->next) {
900                 bool drag_prev = false;
901                 bool drag_curr = false;
902
903                 /* re-set each time */
904                 if (but->flag & UI_BUT_DRAG_MULTI) {
905                         but->flag &= ~UI_BUT_DRAG_MULTI;
906                         drag_prev = true;
907                 }
908
909                 if (ui_is_but_interactive(but, false)) {
910
911                         /* drag checks */
912                         if (but_active != but) {
913                                 if (ui_is_but_compatible(but_active, but)) {
914
915                                         BLI_assert(but->active == NULL);
916
917                                         /* finally check for overlap */
918                                         if (BLI_rctf_isect_segment(&but->rect, seg[0], seg[1])) {
919
920                                                 but->flag |= UI_BUT_DRAG_MULTI;
921                                                 data->multi_data.has_mbuts = true;
922                                                 drag_curr = true;
923                                         }
924                                 }
925                         }
926                 }
927
928                 changed |= (drag_prev != drag_curr);
929         }
930
931         return changed;
932 }
933
934 static void ui_multibut_states_create(uiBut *but_active, uiHandleButtonData *data)
935 {
936         uiBut *but;
937
938         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
939
940         data->multi_data.bs_mbuts = UI_butstore_create(but_active->block);
941
942         for (but = but_active->block->buttons.first; but; but = but->next) {
943                 if (but->flag & UI_BUT_DRAG_MULTI) {
944                         ui_multibut_add(data, but);
945                 }
946         }
947
948         /* edit buttons proportionally to eachother
949          * note: if we mix buttons which are proportional and others which are not,
950          * this may work a bit strangely */
951         if (but_active->rnaprop) {
952                 if ((data->origvalue != 0.0) && (RNA_property_flag(but_active->rnaprop) & PROP_PROPORTIONAL)) {
953                         data->multi_data.is_proportional = true;
954                 }
955         }
956 }
957
958 static void ui_multibut_states_apply(bContext *C, uiHandleButtonData *data, uiBlock *block)
959 {
960         ARegion *ar = data->region;
961         const double value_delta = data->value - data->origvalue;
962         const double value_scale = data->multi_data.is_proportional ? (data->value / data->origvalue) : 0.0;
963         uiBut *but;
964
965         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_ENABLE);
966
967         for (but = block->buttons.first; but; but = but->next) {
968                 if (but->flag & UI_BUT_DRAG_MULTI) {
969                         /* mbut_states for delta */
970                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
971
972                         if (mbut_state) {
973                                 void *active_back;
974
975                                 ui_button_execute_begin(C, ar, but, &active_back);
976                                 BLI_assert(active_back == NULL);
977                                 /* no need to check 'data->state' here */
978                                 if (data->str) {
979                                         /* entering text (set all) */
980                                         but->active->value = data->value;
981                                         ui_set_but_string(C, but, data->str);
982                                 }
983                                 else {
984                                         /* dragging (use delta) */
985                                         if (data->multi_data.is_proportional) {
986                                                 but->active->value = mbut_state->origvalue * value_scale;
987                                         }
988                                         else {
989                                                 but->active->value = mbut_state->origvalue + value_delta;
990                                         }
991
992                                         /* clamp based on soft limits, see: T40154 */
993                                         CLAMP(but->active->value, (double)but->softmin, (double)but->softmax);
994                                 }
995                                 ui_button_execute_end(C, ar, but, active_back);
996                         }
997                         else {
998                                 /* highly unlikely */
999                                 printf("%s: cant find button\n", __func__);
1000                         }
1001                         /* end */
1002
1003                 }
1004         }
1005 }
1006
1007 #endif  /* USE_DRAG_MULTINUM */
1008
1009
1010 #ifdef USE_DRAG_TOGGLE
1011
1012 typedef struct uiDragToggleHandle {
1013         /* init */
1014         bool is_init;
1015         bool is_set;
1016         float but_cent_start[2];
1017         eButType but_type_start;
1018
1019         bool xy_lock[2];
1020         int  xy_init[2];
1021         int  xy_last[2];
1022 } uiDragToggleHandle;
1023
1024 static bool ui_drag_toggle_set_xy_xy(bContext *C, ARegion *ar, const bool is_set, const eButType but_type_start,
1025                                      const int xy_src[2], const int xy_dst[2])
1026 {
1027         /* popups such as layers won't re-evaluate on redraw */
1028         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
1029         bool changed = false;
1030         uiBlock *block;
1031
1032         for (block = ar->uiblocks.first; block; block = block->next) {
1033                 uiBut *but;
1034
1035                 float xy_a_block[2] = {UNPACK2(xy_src)};
1036                 float xy_b_block[2] = {UNPACK2(xy_dst)};
1037
1038                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
1039                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
1040
1041                 for (but = block->buttons.first; but; but = but->next) {
1042                         /* Note: ctrl is always true here because (at least for now) we always want to consider text control
1043                          *       in this case, even when not embossed. */
1044                         if (ui_is_but_interactive(but, true)) {
1045                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
1046
1047                                         /* execute the button */
1048                                         if (ui_is_but_bool(but) && but->type == but_type_start) {
1049                                                 /* is it pressed? */
1050                                                 bool is_set_but = ui_is_but_push(but);
1051                                                 BLI_assert(ui_is_but_bool(but) == true);
1052                                                 if (is_set_but != is_set) {
1053                                                         uiButExecute(C, but);
1054                                                         if (do_check) {
1055                                                                 ui_check_but(but);
1056                                                         }
1057                                                         changed = true;
1058                                                 }
1059                                         }
1060                                         /* done */
1061
1062                                 }
1063                         }
1064                 }
1065         }
1066
1067         return changed;
1068 }
1069
1070 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
1071 {
1072         ARegion *ar = CTX_wm_region(C);
1073         bool do_draw = false;
1074         int xy[2];
1075
1076         /**
1077          * Initialize Locking:
1078          *
1079          * Check if we need to initialize the lock axis by finding if the first
1080          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
1081          */
1082         if (drag_info->is_init == false) {
1083                 /* first store the buttons original coords */
1084                 uiBut *but = ui_but_find_mouse_over_ex(ar, xy_input[0], xy_input[1], true);
1085
1086                 if (but) {
1087                         if (but->flag & UI_BUT_DRAG_LOCK) {
1088                                 const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect),
1089                                                                BLI_rctf_cent_y(&but->rect)};
1090
1091                                 /* check if this is a different button, chances are high the button wont move about :) */
1092                                 if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
1093                                         if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
1094                                             fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
1095                                         {
1096                                                 drag_info->xy_lock[0] = true;
1097                                         }
1098                                         else {
1099                                                 drag_info->xy_lock[1] = true;
1100                                         }
1101                                         drag_info->is_init = true;
1102                                 }
1103                         }
1104                         else {
1105                                 drag_info->is_init = true;
1106                         }
1107                 }
1108         }
1109         /* done with axis locking */
1110
1111
1112         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
1113         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
1114
1115
1116         /* touch all buttons between last mouse coord and this one */
1117         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->but_type_start, drag_info->xy_last, xy);
1118
1119         if (do_draw) {
1120                 ED_region_tag_redraw(ar);
1121         }
1122
1123         copy_v2_v2_int(drag_info->xy_last, xy);
1124 }
1125
1126 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
1127 {
1128         uiDragToggleHandle *drag_info = userdata;
1129         MEM_freeN(drag_info);
1130 }
1131
1132 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
1133 {
1134         uiDragToggleHandle *drag_info = userdata;
1135         bool done = false;
1136
1137         switch (event->type) {
1138                 case LEFTMOUSE:
1139                 {
1140                         if (event->val != KM_PRESS) {
1141                                 done = true;
1142                         }
1143                         break;
1144                 }
1145                 case MOUSEMOVE:
1146                 {
1147                         ui_drag_toggle_set(C, drag_info, &event->x);
1148                         break;
1149                 }
1150         }
1151
1152         if (done) {
1153                 wmWindow *win = CTX_wm_window(C);
1154                 ARegion *ar = CTX_wm_region(C);
1155                 uiBut *but = ui_but_find_mouse_over_ex(ar, drag_info->xy_init[0], drag_info->xy_init[1], true);
1156
1157                 if (but) {
1158                         ui_apply_undo(but);
1159                 }
1160
1161                 WM_event_remove_ui_handler(&win->modalhandlers,
1162                                            ui_handler_region_drag_toggle,
1163                                            ui_handler_region_drag_toggle_remove,
1164                                            drag_info, false);
1165                 ui_handler_region_drag_toggle_remove(C, drag_info);
1166
1167                 WM_event_add_mousemove(C);
1168                 return WM_UI_HANDLER_BREAK;
1169         }
1170         else {
1171                 return WM_UI_HANDLER_CONTINUE;
1172         }
1173 }
1174
1175 static bool ui_is_but_drag_toggle(const uiBut *but)
1176 {
1177         return ((ui_is_but_bool(but) == true) &&
1178                 /* menu check is importnt so the button dragged over isn't removed instantly */
1179                 (ui_block_is_menu(but->block) == false));
1180 }
1181
1182 #endif  /* USE_DRAG_TOGGLE */
1183
1184
1185 static bool ui_but_mouse_inside_icon(uiBut *but, ARegion *ar, const wmEvent *event)
1186 {
1187         rcti rect;
1188         int x = event->x, y = event->y;
1189         
1190         ui_window_to_block(ar, but->block, &x, &y);
1191         
1192         BLI_rcti_rctf_copy(&rect, &but->rect);
1193         
1194         if (but->imb || but->type == COLOR) {
1195                 /* use button size itself */
1196         }
1197         else if (but->drawflag & UI_BUT_ICON_LEFT) {
1198                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
1199         }
1200         else {
1201                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
1202                 rect.xmin += delta / 2;
1203                 rect.xmax -= delta / 2;
1204         }
1205         
1206         return BLI_rcti_isect_pt(&rect, x, y);
1207 }
1208
1209 static bool ui_but_start_drag(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
1210 {
1211         /* prevent other WM gestures to start while we try to drag */
1212         WM_gestures_remove(C);
1213
1214         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
1215
1216                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1217                 data->cancel = true;
1218 #ifdef USE_DRAG_TOGGLE
1219                 if (ui_is_but_bool(but)) {
1220                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1221                         ARegion *ar_prev;
1222
1223                         /* call here because regular mouse-up event wont run,
1224                          * typically 'button_activate_exit()' handles this */
1225                         ui_apply_autokey(C, but);
1226
1227                         drag_info->is_set = ui_is_but_push(but);
1228                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
1229                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
1230                         drag_info->but_type_start = but->type;
1231                         copy_v2_v2_int(drag_info->xy_init, &event->x);
1232                         copy_v2_v2_int(drag_info->xy_last, &event->x);
1233
1234                         /* needed for toggle drag on popups */
1235                         ar_prev = CTX_wm_region(C);
1236                         CTX_wm_region_set(C, data->region);
1237
1238                         WM_event_add_ui_handler(C, &data->window->modalhandlers,
1239                                                 ui_handler_region_drag_toggle,
1240                                                 ui_handler_region_drag_toggle_remove,
1241                                                 drag_info);
1242
1243                         CTX_wm_region_set(C, ar_prev);
1244                 }
1245                 else
1246 #endif
1247                 if (but->type == COLOR) {
1248                         bool valid = false;
1249                         uiDragColorHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1250
1251                         /* TODO support more button pointer types */
1252                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
1253                                 RNA_property_float_get_array(&but->rnapoin, but->rnaprop, drag_info->color);
1254                                 drag_info->gamma_corrected = true;
1255                                 valid = true;
1256                         }
1257                         else if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR) {
1258                                 RNA_property_float_get_array(&but->rnapoin, but->rnaprop, drag_info->color);
1259                                 drag_info->gamma_corrected = false;
1260                                 valid = true;
1261                         }
1262                         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1263                                 copy_v3_v3(drag_info->color, (float *)but->poin);
1264                                 valid = true;
1265                         }
1266                         else if (but->pointype == UI_BUT_POIN_CHAR) {
1267                                 rgba_uchar_to_float(drag_info->color, (unsigned char *)but->poin);
1268                                 valid = true;
1269                         }
1270
1271                         if (valid) {
1272                                 WM_event_start_drag(C, ICON_COLOR, WM_DRAG_COLOR, drag_info, 0.0, WM_DRAG_FREE_DATA);
1273                         }
1274                         else {
1275                                 MEM_freeN(drag_info);
1276                                 return false;
1277                         }
1278                 }
1279                 else {
1280                         wmDrag *drag;
1281
1282                         drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_get_but_val(but), WM_DRAG_NOP);
1283                         if (but->imb)
1284                                 WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
1285                 }
1286                 return true;
1287         }
1288         
1289         return false;
1290 }
1291
1292 /* ********************** linklines *********************** */
1293
1294 static void ui_delete_active_linkline(uiBlock *block)
1295 {
1296         uiBut *but;
1297         uiLink *link;
1298         uiLinkLine *line, *nline;
1299         int a, b;
1300
1301         for (but = block->buttons.first; but; but = but->next) {
1302                 if (but->type == LINK && but->link) {
1303                         for (line = but->link->lines.first; line; line = nline) {
1304                                 nline = line->next;
1305                                 
1306                                 if (line->flag & UI_SELECT) {
1307                                         BLI_remlink(&but->link->lines, line);
1308                                         
1309                                         link = line->from->link;
1310                                         
1311                                         /* are there more pointers allowed? */
1312                                         if (link->ppoin) {
1313                                                 
1314                                                 if (*(link->totlink) == 1) {
1315                                                         *(link->totlink) = 0;
1316                                                         MEM_freeN(*(link->ppoin));
1317                                                         *(link->ppoin) = NULL;
1318                                                 }
1319                                                 else {
1320                                                         b = 0;
1321                                                         for (a = 0; a < (*(link->totlink)); a++) {
1322                                                                 
1323                                                                 if ((*(link->ppoin))[a] != line->to->poin) {
1324                                                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1325                                                                         b++;
1326                                                                 }
1327                                                         }
1328                                                         (*(link->totlink))--;
1329                                                 }
1330                                         }
1331                                         else {
1332                                                 *(link->poin) = NULL;
1333                                         }
1334                                         
1335                                         MEM_freeN(line);
1336                                 }
1337                         }
1338                 }
1339         }
1340 }
1341
1342
1343 static uiLinkLine *ui_is_a_link(uiBut *from, uiBut *to)
1344 {
1345         uiLinkLine *line;
1346         uiLink *link;
1347         
1348         link = from->link;
1349         if (link) {
1350                 for (line = link->lines.first; line; line = line->next) {
1351                         if (line->from == from && line->to == to) {
1352                                 return line;
1353                         }
1354                 }
1355         }
1356         return NULL;
1357 }
1358
1359 /* XXX BAD BAD HACK, fixme later **************** */
1360 /* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */
1361 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
1362 {
1363         Object *ob = NULL;
1364         bSensor *sens_iter;
1365         bActuator *act_to, *act_iter;
1366         bController *cont;
1367         bController ***sens_from_links;
1368         uiBut *tmp_but;
1369
1370         uiLink *link = from->link;
1371
1372         PointerRNA props_ptr, object_ptr;
1373         
1374         if (link->ppoin)
1375                 sens_from_links = (bController ***)(link->ppoin);
1376         else return;
1377
1378         act_to = (bActuator *)(to->poin);
1379
1380         /* (1) get the object */
1381         CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects)
1382         {
1383                 for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) {
1384                         if (&(sens_iter->links) == sens_from_links) {
1385                                 ob = ob_iter;
1386                                 break;
1387                         }
1388                 }
1389                 if (ob) break;
1390         } CTX_DATA_END;
1391
1392         if (!ob) return;
1393
1394         /* (2) check if the sensor and the actuator are from the same object */
1395         for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) {
1396                 if (act_iter == act_to)
1397                         break;
1398         }
1399
1400         /* only works if the sensor and the actuator are from the same object */
1401         if (!act_iter) return;
1402         
1403         /* in case the linked controller is not the active one */
1404         RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
1405         
1406         WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
1407         RNA_string_set(&props_ptr, "object", ob->id.name + 2);
1408
1409         /* (3) add a new controller */
1410         if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
1411                 cont = (bController *)ob->controllers.last;
1412                 cont->type = CONT_LOGIC_AND; /* Quick fix to make sure we always have an AND controller. It might be nicer to make sure the operator gives us the right one though... */
1413
1414                 /* (4) link the sensor->controller->actuator */
1415                 tmp_but = MEM_callocN(sizeof(uiBut), "uiBut");
1416                 uiSetButLink(tmp_but, (void **)&cont, (void ***)&(cont->links), &(cont->totlinks), from->link->tocode, (int)to->hardmin);
1417                 tmp_but->hardmin = from->link->tocode;
1418                 tmp_but->poin = (char *)cont;
1419
1420                 tmp_but->type = INLINK;
1421                 ui_add_link(C, from, tmp_but);
1422
1423                 tmp_but->type = LINK;
1424                 ui_add_link(C, tmp_but, to);
1425
1426                 /* (5) garbage collection */
1427                 MEM_freeN(tmp_but->link);
1428                 MEM_freeN(tmp_but);
1429         }
1430         WM_operator_properties_free(&props_ptr);
1431 }
1432
1433 static void ui_add_link(bContext *C, uiBut *from, uiBut *to)
1434 {
1435         /* in 'from' we have to add a link to 'to' */
1436         uiLink *link;
1437         uiLinkLine *line;
1438         void **oldppoin;
1439         int a;
1440         
1441         if ((line = ui_is_a_link(from, to))) {
1442                 line->flag |= UI_SELECT;
1443                 ui_delete_active_linkline(from->block);
1444                 return;
1445         }
1446
1447         if (from->type == INLINK && to->type == INLINK) {
1448                 return;
1449         }
1450         else if (from->type == LINK && to->type == INLINK) {
1451                 if (from->link->tocode != (int)to->hardmin) {
1452                         ui_add_smart_controller(C, from, to);
1453                         return;
1454                 }
1455         }
1456         else if (from->type == INLINK && to->type == LINK) {
1457                 if (to->link->tocode == (int)from->hardmin) {
1458                         return;
1459                 }
1460         }
1461         
1462         link = from->link;
1463         
1464         /* are there more pointers allowed? */
1465         if (link->ppoin) {
1466                 oldppoin = *(link->ppoin);
1467                 
1468                 (*(link->totlink))++;
1469                 *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link");
1470                 
1471                 for (a = 0; a < (*(link->totlink)) - 1; a++) {
1472                         (*(link->ppoin))[a] = oldppoin[a];
1473                 }
1474                 (*(link->ppoin))[a] = to->poin;
1475                 
1476                 if (oldppoin) MEM_freeN(oldppoin);
1477         }
1478         else {
1479                 *(link->poin) = to->poin;
1480         }
1481         
1482 }
1483
1484
1485 static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data)
1486 {
1487         ARegion *ar = CTX_wm_region(C);
1488         uiBut *bt;
1489         
1490         for (bt = but->block->buttons.first; bt; bt = bt->next) {
1491                 if (ui_mouse_inside_button(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) )
1492                         break;
1493         }
1494         if (bt && bt != but) {
1495                 if (!ELEM(bt->type, LINK, INLINK) || !ELEM(but->type, LINK, INLINK))
1496                         return;
1497                 
1498                 if (but->type == LINK) ui_add_link(C, but, bt);
1499                 else ui_add_link(C, bt, but);
1500
1501                 ui_apply_but_func(C, but);
1502                 data->retval = but->retval;
1503         }
1504         data->applied = true;
1505 }
1506
1507 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1508 {
1509         ui_apply_but_func(C, but);
1510         data->retval = but->retval;
1511         data->applied = true;
1512 }
1513
1514 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1515 {
1516         ui_apply_but_func(C, but);
1517         data->retval = but->retval;
1518         data->applied = true;
1519 }
1520
1521 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1522 {
1523         ui_apply_but_func(C, but);
1524         data->retval = but->retval;
1525         data->applied = true;
1526 }
1527
1528 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1529 {
1530         ui_apply_but_func(C, but);
1531         data->retval = but->retval;
1532         data->applied = true;
1533 }
1534
1535
1536 static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1537 {
1538         char *editstr;
1539         double *editval;
1540         float *editvec;
1541         ColorBand *editcoba;
1542         CurveMapping *editcumap;
1543
1544         data->retval = 0;
1545
1546         /* if we cancel and have not applied yet, there is nothing to do,
1547          * otherwise we have to restore the original value again */
1548         if (data->cancel) {
1549                 if (!data->applied)
1550                         return;
1551
1552                 if (data->str) MEM_freeN(data->str);
1553                 data->str = data->origstr;
1554                 data->origstr = NULL;
1555                 data->value = data->origvalue;
1556                 data->origvalue = 0.0;
1557                 copy_v3_v3(data->vec, data->origvec);
1558                 data->origvec[0] = data->origvec[1] = data->origvec[2] = 0.0f;
1559         }
1560         else {
1561                 /* we avoid applying interactive edits a second time
1562                  * at the end with the appliedinteractive flag */
1563                 if (interactive) {
1564                         data->applied_interactive = true;
1565                 }
1566                 else if (data->applied_interactive) {
1567                         return;
1568                 }
1569         }
1570
1571         /* ensures we are writing actual values */
1572         editstr = but->editstr;
1573         editval = but->editval;
1574         editvec = but->editvec;
1575         editcoba = but->editcoba;
1576         editcumap = but->editcumap;
1577         but->editstr = NULL;
1578         but->editval = NULL;
1579         but->editvec = NULL;
1580         but->editcoba = NULL;
1581         but->editcumap = NULL;
1582
1583         /* handle different types */
1584         switch (but->type) {
1585                 case BUT:
1586                         ui_apply_but_BUT(C, but, data);
1587                         break;
1588                 case TEX:
1589                 case SEARCH_MENU_UNLINK:
1590                 case SEARCH_MENU:
1591                         ui_apply_but_TEX(C, but, data);
1592                         break;
1593                 case TOGBUT: 
1594                 case TOG: 
1595                 case ICONTOG:
1596                 case ICONTOGN:
1597                 case TOGN:
1598                 case OPTION:
1599                 case OPTIONN:
1600                         ui_apply_but_TOG(C, but, data);
1601                         break;
1602                 case ROW:
1603                 case LISTROW:
1604                         ui_apply_but_ROW(C, block, but, data);
1605                         break;
1606                 case SCROLL:
1607                 case GRIP:
1608                 case NUM:
1609                 case NUMSLI:
1610                         ui_apply_but_NUM(C, but, data);
1611                         break;
1612                 case MENU:
1613                 case BLOCK:
1614                 case PULLDOWN:
1615                         ui_apply_but_BLOCK(C, but, data);
1616                         break;
1617                 case COLOR:
1618                         if (data->cancel)
1619                                 ui_apply_but_VEC(C, but, data);
1620                         else
1621                                 ui_apply_but_BLOCK(C, but, data);
1622                         break;
1623                 case BUTM:
1624                         ui_apply_but_BUTM(C, but, data);
1625                         break;
1626                 case BUT_NORMAL:
1627                 case HSVCUBE:
1628                 case HSVCIRCLE:
1629                         ui_apply_but_VEC(C, but, data);
1630                         break;
1631                 case BUT_COLORBAND:
1632                         ui_apply_but_COLORBAND(C, but, data);
1633                         break;
1634                 case BUT_CURVE:
1635                         ui_apply_but_CURVE(C, but, data);
1636                         break;
1637                 case KEYEVT:
1638                 case HOTKEYEVT:
1639                         ui_apply_but_BUT(C, but, data);
1640                         break;
1641                 case LINK:
1642                 case INLINK:
1643                         ui_apply_but_LINK(C, but, data);
1644                         break;
1645                 case BUT_IMAGE:
1646                         ui_apply_but_IMAGE(C, but, data);
1647                         break;
1648                 case HISTOGRAM:
1649                         ui_apply_but_HISTOGRAM(C, but, data);
1650                         break;
1651                 case WAVEFORM:
1652                         ui_apply_but_WAVEFORM(C, but, data);
1653                         break;
1654                 case TRACKPREVIEW:
1655                         ui_apply_but_TRACKPREVIEW(C, but, data);
1656                         break;
1657                 default:
1658                         break;
1659         }
1660
1661 #ifdef USE_DRAG_MULTINUM
1662         if (data->multi_data.has_mbuts) {
1663                 if (data->multi_data.init == BUTTON_MULTI_INIT_ENABLE) {
1664                         if (data->cancel) {
1665                                 ui_multibut_restore(data, block);
1666                         }
1667                         else {
1668                                 ui_multibut_states_apply(C, data, block);
1669                         }
1670                 }
1671         }
1672 #endif
1673
1674         but->editstr = editstr;
1675         but->editval = editval;
1676         but->editvec = editvec;
1677         but->editcoba = editcoba;
1678         but->editcumap = editcumap;
1679 }
1680
1681 /* ******************* drop event ********************  */
1682
1683 /* only call if event type is EVT_DROP */
1684 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
1685 {
1686         wmDrag *wmd;
1687         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
1688         
1689         for (wmd = drags->first; wmd; wmd = wmd->next) {
1690                 if (wmd->type == WM_DRAG_ID) {
1691                         /* align these types with UI_but_active_drop_name */
1692                         if (ELEM(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1693                                 ID *id = (ID *)wmd->poin;
1694                                 
1695                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1696                                 BLI_strncpy(data->str, id->name + 2, data->maxlen);
1697
1698                                 if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1699                                         but->changed = true;
1700                                         ui_searchbox_update(C, data->searchbox, but, true);
1701                                 }
1702
1703                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1704                         }
1705                 }
1706         }
1707         
1708 }
1709
1710 /* ******************* copy and paste ********************  */
1711
1712 /* c = copy, v = paste */
1713 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, char mode)
1714 {
1715         int buf_paste_len = 0;
1716         const char *buf_paste = "";
1717         bool buf_paste_alloc = false;
1718
1719         if (mode == 'v' && but->lock  == true) {
1720                 return;
1721         }
1722
1723         if (mode == 'c') {
1724                 /* disallow copying from any passwords */
1725                 if (but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD)) {
1726                         return;
1727                 }
1728         }
1729
1730         if (mode == 'v') {
1731                 /* extract first line from clipboard in case of multi-line copies */
1732                 const char *buf_paste_test;
1733
1734                 buf_paste_test = WM_clipboard_text_get_firstline(false, &buf_paste_len);
1735                 if (buf_paste_test) {
1736                         buf_paste = buf_paste_test;
1737                         buf_paste_alloc = true;
1738                 }
1739         }
1740
1741         /* No return from here down */
1742
1743
1744         /* numeric value */
1745         if (ELEM(but->type, NUM, NUMSLI)) {
1746                 
1747                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1748                         /* pass */
1749                 }
1750                 else if (mode == 'c') {
1751                         /* Get many decimal places, then strip trailing zeros.
1752                          * note: too high values start to give strange results (6 or so is ok) */
1753                         char buf_copy[UI_MAX_DRAW_STR];
1754                         ui_get_but_string_ex(but, buf_copy, sizeof(buf_copy), 6);
1755                         BLI_str_rstrip_float_zero(buf_copy, '\0');
1756
1757                         WM_clipboard_text_set(buf_copy, 0);
1758                 }
1759                 else {
1760                         double val;
1761
1762                         if (ui_set_but_string_eval_num(C, but, buf_paste, &val)) {
1763                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1764                                 data->value = val;
1765                                 ui_set_but_string(C, but, buf_paste);
1766                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1767                         }
1768                 }
1769         }
1770
1771         /* NORMAL button */
1772         else if (but->type == BUT_NORMAL) {
1773                 float xyz[3];
1774
1775                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1776                         /* pass */
1777                 }
1778                 else if (mode == 'c') {
1779                         char buf_copy[UI_MAX_DRAW_STR];
1780                         ui_get_but_vectorf(but, xyz);
1781                         BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f]", xyz[0], xyz[1], xyz[2]);
1782                         WM_clipboard_text_set(buf_copy, 0);
1783                 }
1784                 else {
1785                         if (sscanf(buf_paste, "[%f, %f, %f]", &xyz[0], &xyz[1], &xyz[2]) == 3) {
1786                                 if (normalize_v3(xyz) == 0.0f) {
1787                                         /* better set Z up then have a zero vector */
1788                                         xyz[2] = 1.0;
1789                                 }
1790                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1791                                 ui_set_but_vectorf(but, xyz);
1792                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1793                         }
1794                 }
1795         }
1796
1797
1798         /* RGB triple */
1799         else if (but->type == COLOR) {
1800                 float rgba[4];
1801                 
1802                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1803                         /* pass */
1804                 }
1805                 else if (mode == 'c') {
1806                         char buf_copy[UI_MAX_DRAW_STR];
1807
1808                         if (but->rnaprop && RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1809                                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
1810                         else
1811                                 rgba[3] = 1.0f;
1812                         
1813                         ui_get_but_vectorf(but, rgba);
1814                         /* convert to linear color to do compatible copy between gamma and non-gamma */
1815                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1816                                 srgb_to_linearrgb_v3_v3(rgba, rgba);
1817
1818                         BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f, %f]", rgba[0], rgba[1], rgba[2], rgba[3]);
1819                         WM_clipboard_text_set(buf_copy, 0);
1820                         
1821                 }
1822                 else {
1823                         if (sscanf(buf_paste, "[%f, %f, %f, %f]", &rgba[0], &rgba[1], &rgba[2], &rgba[3]) == 4) {
1824                                 /* assume linear colors in buffer */
1825                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1826                                         linearrgb_to_srgb_v3_v3(rgba, rgba);
1827
1828                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1829                                 ui_set_but_vectorf(but, rgba);
1830                                 if (but->rnaprop && RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
1831                                         RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, rgba[3]);
1832
1833                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1834                         }
1835                 }
1836         }
1837
1838         /* text/string and ID data */
1839         else if (ELEM(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1840                 uiHandleButtonData *active_data = but->active;
1841
1842                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1843                         /* pass */
1844                 }
1845                 else if (mode == 'c') {
1846                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1847                         WM_clipboard_text_set(active_data->str, 0);
1848                         active_data->cancel = true;
1849                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1850                 }
1851                 else {
1852                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1853
1854                         if (ui_is_but_utf8(but))
1855                                 BLI_strncpy_utf8(active_data->str, buf_paste, active_data->maxlen);
1856                         else
1857                                 BLI_strncpy(active_data->str, buf_paste, active_data->maxlen);
1858
1859                         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1860                                 /* else uiSearchboxData.active member is not updated [#26856] */
1861                                 but->changed = true;
1862                                 ui_searchbox_update(C, data->searchbox, but, true);
1863                         }
1864                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1865                 }
1866         }
1867         /* colorband (not supported by system clipboard) */
1868         else if (but->type == BUT_COLORBAND) {
1869                 if (mode == 'c') {
1870                         if (but->poin != NULL) {
1871                                 memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
1872                         }
1873                 }
1874                 else {
1875                         if (but_copypaste_coba.tot != 0) {
1876                                 if (!but->poin)
1877                                         but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
1878
1879                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1880                                 memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
1881                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1882                         }
1883                 }
1884         }
1885         else if (but->type == BUT_CURVE) {
1886                 if (mode == 'c') {
1887                         if (but->poin != NULL) {
1888                                 but_copypaste_curve_alive = true;
1889                                 curvemapping_free_data(&but_copypaste_curve);
1890                                 curvemapping_copy_data(&but_copypaste_curve, (CurveMapping *) but->poin);
1891                         }
1892                 }
1893                 else {
1894                         if (but_copypaste_curve_alive) {
1895                                 if (!but->poin)
1896                                         but->poin = MEM_callocN(sizeof(CurveMapping), "curvemapping");
1897
1898                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1899                                 curvemapping_free_data((CurveMapping *) but->poin);
1900                                 curvemapping_copy_data((CurveMapping *) but->poin, &but_copypaste_curve);
1901                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1902                         }
1903                 }
1904         }
1905         /* operator button (any type) */
1906         else if (but->optype) {
1907                 if (mode == 'c') {
1908                         PointerRNA *opptr;
1909                         char *str;
1910                         opptr = uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
1911
1912                         str = WM_operator_pystring_ex(C, NULL, false, true, but->optype, opptr);
1913
1914                         WM_clipboard_text_set(str, 0);
1915
1916                         MEM_freeN(str);
1917                 }
1918         }
1919         /* menu (any type) */
1920         else if (ELEM(but->type, MENU, PULLDOWN)) {
1921                 MenuType *mt = uiButGetMenuType(but);
1922                 if (mt) {
1923                         char str[32 + sizeof(mt->idname)];
1924                         BLI_snprintf(str, sizeof(str), "bpy.ops.wm.call_menu(name=\"%s\")", mt->idname);
1925                         WM_clipboard_text_set(str, 0);
1926                 }
1927         }
1928
1929         if (buf_paste_alloc) {
1930                 MEM_freeN((void *)buf_paste);
1931         }
1932 }
1933
1934 /* ************************ password text ******************************
1935  *
1936  * Functions to convert password strings that should not be displayed
1937  * to asterisk representation (e.g. mysecretpasswd -> *************)
1938  *
1939  * It converts every UTF-8 character to an asterisk, and also remaps
1940  * the cursor position and selection start/end.
1941  *
1942  * Note: remaping is used, because password could contain UTF-8 characters.
1943  *
1944  */
1945
1946 static int ui_text_position_from_hidden(uiBut *but, int pos)
1947 {
1948         const char *strpos;
1949         int i;
1950
1951         for (i = 0, strpos = but->drawstr; i < pos; i++)
1952                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
1953         
1954         return (strpos - but->drawstr);
1955 }
1956
1957 static int ui_text_position_to_hidden(uiBut *but, int pos)
1958 {
1959         return BLI_strnlen_utf8(but->drawstr, pos);
1960 }
1961
1962 void ui_button_text_password_hide(char password_str[UI_MAX_DRAW_STR], uiBut *but, const bool restore)
1963 {
1964         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
1965                 return;
1966
1967         if (restore) {
1968                 /* restore original string */
1969                 BLI_strncpy(but->drawstr, password_str, UI_MAX_DRAW_STR);
1970
1971                 /* remap cursor positions */
1972                 if (but->pos >= 0) {
1973                         but->pos = ui_text_position_from_hidden(but, but->pos);
1974                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
1975                         but->selend = ui_text_position_from_hidden(but, but->selend);
1976                 }
1977         }
1978         else {
1979                 /* convert text to hidden test using asterisks (e.g. pass -> ****) */
1980                 const size_t len = BLI_strlen_utf8(but->drawstr);
1981
1982                 /* remap cursor positions */
1983                 if (but->pos >= 0) {
1984                         but->pos = ui_text_position_to_hidden(but, but->pos);
1985                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
1986                         but->selend = ui_text_position_to_hidden(but, but->selend);
1987                 }
1988
1989                 /* save original string */
1990                 BLI_strncpy(password_str, but->drawstr, UI_MAX_DRAW_STR);
1991
1992                 memset(but->drawstr, '*', len);
1993                 but->drawstr[len] = '\0';
1994         }
1995 }
1996
1997
1998 /* ************* in-button text selection/editing ************* */
1999
2000
2001 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
2002 {
2003         char *str = data->str;
2004         const int len = strlen(str);
2005         bool changed = false;
2006         if (but->selsta != but->selend && len) {
2007                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
2008                 changed = true;
2009         }
2010         
2011         but->pos = but->selend = but->selsta;
2012         return changed;
2013 }
2014
2015 /**
2016  * \param x  Screen space cursor location - #wmEvent.x
2017  *
2018  * \note ``but->block->aspect`` is used here, so drawing button style is getting scaled too.
2019  */
2020 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
2021 {
2022         uiStyle *style = UI_GetStyle();  // XXX pass on as arg
2023         uiFontStyle *fstyle = &style->widget;
2024         const float aspect = but->block->aspect;
2025         const short fstyle_points_prev = fstyle->points;
2026
2027         float startx = but->rect.xmin;
2028         float starty_dummy = 0.0f;
2029         char *origstr, password_str[UI_MAX_DRAW_STR];
2030
2031         ui_block_to_window_fl(data->region, but->block, &startx, &starty_dummy);
2032
2033         ui_fontscale(&fstyle->points, aspect);
2034
2035         uiStyleFontSet(fstyle);
2036
2037         if (fstyle->kerning == 1) /* for BLF_width */
2038                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2039         
2040         ui_button_text_password_hide(password_str, but, false);
2041
2042         origstr = MEM_mallocN(sizeof(char) * data->maxlen, "ui_textedit origstr");
2043
2044         BLI_strncpy(origstr, but->editstr, data->maxlen);
2045
2046         if (ELEM(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2047                 if (but->flag & UI_HAS_ICON) {
2048                         startx += UI_DPI_ICON_SIZE / aspect;
2049                 }
2050         }
2051         /* but this extra .05 makes clicks inbetween characters feel nicer */
2052         startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit) / aspect;
2053         
2054         /* mouse dragged outside the widget to the left */
2055         if (x < startx) {
2056                 int i = but->ofs;
2057
2058                 origstr[but->ofs] = '\0';
2059                 
2060                 while (i > 0) {
2061                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &i)) {
2062                                 /* 0.25 == scale factor for less sensitivity */
2063                                 if (BLF_width(fstyle->uifont_id, origstr + i, BLF_DRAW_STR_DUMMY_MAX) > (startx - x) * 0.25f) {
2064                                         break;
2065                                 }
2066                         }
2067                         else {
2068                                 break; /* unlikely but possible */
2069                         }
2070                 }
2071                 but->ofs = i;
2072                 but->pos = but->ofs;
2073         }
2074         /* mouse inside the widget, mouse coords mapped in widget space */
2075         else {  /* (x >= startx) */
2076                 int pos_i;
2077
2078                 /* keep track of previous distance from the cursor to the char */
2079                 float cdist, cdist_prev = 0.0f;
2080                 short pos_prev;
2081                 
2082                 but->pos = pos_prev = strlen(origstr) - but->ofs;
2083
2084                 while (true) {
2085                         cdist = startx + BLF_width(fstyle->uifont_id, origstr + but->ofs, BLF_DRAW_STR_DUMMY_MAX);
2086
2087                         /* check if position is found */
2088                         if (cdist < x) {
2089                                 /* check is previous location was in fact closer */
2090                                 if ((x - cdist) > (cdist_prev - x)) {
2091                                         but->pos = pos_prev;
2092                                 }
2093                                 break;
2094                         }
2095                         cdist_prev = cdist;
2096                         pos_prev   = but->pos;
2097                         /* done with tricky distance checks */
2098
2099                         pos_i = but->pos;
2100                         if (but->pos <= 0) break;
2101                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &pos_i)) {
2102                                 but->pos = pos_i;
2103                                 origstr[but->pos + but->ofs] = 0;
2104                         }
2105                         else {
2106                                 break; /* unlikely but possible */
2107                         }
2108                 }
2109                 but->pos += but->ofs;
2110                 if (but->pos < 0) but->pos = 0;
2111         }
2112         
2113         if (fstyle->kerning == 1)
2114                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2115         
2116         ui_button_text_password_hide(password_str, but, true);
2117
2118         MEM_freeN(origstr);
2119
2120         fstyle->points = fstyle_points_prev;
2121 }
2122
2123 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
2124 {
2125         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
2126         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
2127
2128         ui_textedit_set_cursor_pos(but, data, x);
2129
2130         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
2131         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
2132
2133         ui_check_but(but);
2134 }
2135
2136 /* this is used for both utf8 and ascii, its meant to be used for single keys,
2137  * notice the buffer is either copied or not, so its not suitable for pasting in
2138  * - campbell */
2139 static bool ui_textedit_type_buf(uiBut *but, uiHandleButtonData *data,
2140                                  const char *utf8_buf, int utf8_buf_len)
2141 {
2142         char *str;
2143         int len;
2144         bool changed = false;
2145
2146         str = data->str;
2147         len = strlen(str);
2148
2149         if (len - (but->selend - but->selsta) + 1 <= data->maxlen) {
2150                 int step = utf8_buf_len;
2151
2152                 /* type over the current selection */
2153                 if ((but->selend - but->selsta) > 0) {
2154                         changed = ui_textedit_delete_selection(but, data);
2155                         len = strlen(str);
2156                 }
2157
2158                 if (len + step < data->maxlen) {
2159                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
2160                         memcpy(&str[but->pos], utf8_buf, step * sizeof(char));
2161                         but->pos += step;
2162                         changed = true;
2163                 }
2164         }
2165
2166         return changed;
2167 }
2168
2169 static bool ui_textedit_type_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
2170 {
2171         char buf[2] = {ascii, '\0'};
2172
2173         if (ui_is_but_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
2174                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
2175                        __func__, (int)(unsigned char)ascii);
2176
2177                 return false;
2178         }
2179
2180         /* in some cases we want to allow invalid utf8 chars */
2181         return ui_textedit_type_buf(but, data, buf, 1);
2182 }
2183
2184 static void ui_textedit_move(uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
2185                              const bool select, strCursorJumpType jump)
2186 {
2187         const char *str = data->str;
2188         const int len = strlen(str);
2189         const int pos_prev = but->pos;
2190         const bool has_sel = (but->selend - but->selsta) > 0;
2191
2192         ui_check_but(but);
2193
2194         /* special case, quit selection and set cursor */
2195         if (has_sel && !select) {
2196                 if (jump == STRCUR_JUMP_ALL) {
2197                         but->selsta = but->selend = but->pos = direction ? len : 0;
2198                 }
2199                 else {
2200                         if (direction) {
2201                                 but->selsta = but->pos = but->selend;
2202                         }
2203                         else {
2204                                 but->pos = but->selend = but->selsta;
2205                         }
2206                 }
2207                 data->selextend = 0;
2208         }
2209         else {
2210                 int pos_i = but->pos;
2211                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
2212                 but->pos = pos_i;
2213
2214                 if (select) {
2215                         /* existing selection */
2216                         if (has_sel) {
2217
2218                                 if (data->selextend == 0) {
2219                                         data->selextend = EXTEND_RIGHT;
2220                                 }
2221
2222                                 if (direction) {
2223                                         if (data->selextend == EXTEND_RIGHT) {
2224                                                 but->selend = but->pos;
2225                                         }
2226                                         else {
2227                                                 but->selsta = but->pos;
2228                                         }
2229                                 }
2230                                 else {
2231                                         if (data->selextend == EXTEND_LEFT) {
2232                                                 but->selsta = but->pos;
2233                                         }
2234                                         else {
2235                                                 but->selend = but->pos;
2236                                         }
2237                                 }
2238
2239                                 if (but->selend < but->selsta) {
2240                                         SWAP(short, but->selsta, but->selend);
2241                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
2242                                 }
2243
2244                         } /* new selection */
2245                         else {
2246                                 if (direction) {
2247                                         data->selextend = EXTEND_RIGHT;
2248                                         but->selend = but->pos;
2249                                         but->selsta = pos_prev;
2250                                 }
2251                                 else {
2252                                         data->selextend = EXTEND_LEFT;
2253                                         but->selend = pos_prev;
2254                                         but->selsta = but->pos;
2255                                 }
2256                         }
2257                 }
2258         }
2259 }
2260
2261 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
2262 {
2263         char *str = data->str;
2264         const int len = strlen(str);
2265
2266         bool changed = false;
2267
2268         if (jump == STRCUR_JUMP_ALL) {
2269                 if (len) changed = true;
2270                 str[0] = '\0';
2271                 but->pos = 0;
2272         }
2273         else if (direction) { /* delete */
2274                 if ((but->selend - but->selsta) > 0) {
2275                         changed = ui_textedit_delete_selection(but, data);
2276                 }
2277                 else if (but->pos >= 0 && but->pos < len) {
2278                         int pos = but->pos;
2279                         int step;
2280                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2281                         step = pos - but->pos;
2282                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - (but->pos + step));
2283                         changed = true;
2284                 }
2285         }
2286         else { /* backspace */
2287                 if (len != 0) {
2288                         if ((but->selend - but->selsta) > 0) {
2289                                 changed = ui_textedit_delete_selection(but, data);
2290                         }
2291                         else if (but->pos > 0) {
2292                                 int pos = but->pos;
2293                                 int step;
2294
2295                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2296                                 step = but->pos - pos;
2297                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
2298                                 but->pos -= step;
2299                                 changed = true;
2300                         }
2301                 }
2302         }
2303
2304         return changed;
2305 }
2306
2307 static int ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
2308 {
2309         char *str;
2310         int changed;
2311
2312         str = data->str;
2313
2314         if (data->searchbox)
2315                 changed = ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
2316         else
2317                 changed = but->autocomplete_func(C, str, but->autofunc_arg);
2318
2319         but->pos = strlen(str);
2320         but->selsta = but->selend = but->pos;
2321
2322         return changed;
2323 }
2324
2325 /* mode for ui_textedit_copypaste() */
2326 enum {
2327         UI_TEXTEDIT_PASTE = 1,
2328         UI_TEXTEDIT_COPY,
2329         UI_TEXTEDIT_CUT
2330 };
2331
2332 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
2333 {
2334         char *str, *pbuf;
2335         int x;
2336         bool changed = false;
2337         int str_len, buf_len;
2338
2339         str = data->str;
2340         str_len = strlen(str);
2341         
2342         /* paste */
2343         if (mode == UI_TEXTEDIT_PASTE) {
2344                 /* TODO, ensure UTF8 ui_is_but_utf8() - campbell */
2345                 /* extract the first line from the clipboard */
2346                 pbuf = WM_clipboard_text_get_firstline(false, &buf_len);
2347
2348                 if (pbuf) {
2349                         char buf[UI_MAX_DRAW_STR] = {0};
2350                         unsigned int y;
2351
2352                         buf_len = BLI_strncpy_rlen(buf, pbuf, sizeof(buf));
2353
2354                         /* paste over the current selection */
2355                         if ((but->selend - but->selsta) > 0) {
2356                                 ui_textedit_delete_selection(but, data);
2357                                 str_len = strlen(str);
2358                         }
2359                         
2360                         for (y = 0; y < buf_len; y++) {
2361                                 /* add contents of buffer */
2362                                 if (str_len + 1 < data->maxlen) {
2363                                         for (x = data->maxlen; x > but->pos; x--)
2364                                                 str[x] = str[x - 1];
2365                                         str[but->pos] = buf[y];
2366                                         but->pos++; 
2367                                         str_len++;
2368                                         str[str_len] = '\0';
2369                                 }
2370                         }
2371
2372                         changed = true;
2373                 }
2374
2375                 if (pbuf) {
2376                         MEM_freeN(pbuf);
2377                 }
2378         }
2379         /* cut & copy */
2380         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
2381                 /* copy the contents to the copypaste buffer */
2382                 int sellen = but->selend - but->selsta;
2383                 char *buf = MEM_mallocN(sizeof(char) * (sellen + 1), "ui_textedit_copypaste");
2384
2385                 BLI_strncpy(buf, str + but->selsta, sellen + 1);
2386                 WM_clipboard_text_set(buf, 0);
2387                 MEM_freeN(buf);
2388                 
2389                 /* for cut only, delete the selection afterwards */
2390                 if (mode == UI_TEXTEDIT_CUT) {
2391                         if ((but->selend - but->selsta) > 0) {
2392                                 changed = ui_textedit_delete_selection(but, data);
2393                         }
2394                 }
2395         }
2396
2397         return changed;
2398 }
2399
2400 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2401 {
2402         int len;
2403
2404         if (data->str) {
2405                 MEM_freeN(data->str);
2406                 data->str = NULL;
2407         }
2408
2409 #ifdef USE_DRAG_MULTINUM
2410         /* this can happen from multi-drag */
2411         if (data->applied_interactive) {
2412                 /* remove any small changes so canceling edit doesn't restore invalid value: T40538 */
2413                 data->cancel = true;
2414                 ui_apply_button(C, but->block, but, data, true);
2415                 data->cancel = false;
2416
2417                 data->applied_interactive = false;
2418         }
2419 #endif
2420
2421         /* retrieve string */
2422         data->maxlen = ui_get_but_string_max_length(but);
2423         data->str = MEM_callocN(sizeof(char) * data->maxlen + 1, "textedit str");
2424         ui_get_but_string(but, data->str, data->maxlen);
2425
2426         if (ui_is_but_float(but) && !ui_is_but_unit(but)) {
2427                 BLI_str_rstrip_float_zero(data->str, '\0');
2428         }
2429
2430         if (ELEM(but->type, NUM, NUMSLI)) {
2431                 ui_convert_to_unit_alt_name(but, data->str, data->maxlen);
2432         }
2433
2434         /* won't change from now on */
2435         len = strlen(data->str);
2436
2437         data->origstr = BLI_strdupn(data->str, len);
2438         data->selextend = 0;
2439         data->selstartx = 0.0f;
2440
2441         /* set cursor pos to the end of the text */
2442         but->editstr = data->str;
2443         but->pos = len;
2444         but->selsta = 0;
2445         but->selend = len;
2446
2447         /* optional searchbox */
2448         if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2449                 data->searchbox = ui_searchbox_create(C, data->region, but);
2450                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
2451         }
2452
2453         /* reset alert flag (avoid confusion, will refresh on exit) */
2454         but->flag &= ~UI_BUT_REDALERT;
2455
2456         ui_check_but(but);
2457         
2458         WM_cursor_modal_set(CTX_wm_window(C), BC_TEXTEDITCURSOR);
2459 }
2460
2461 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2462 {
2463         if (but) {
2464                 if (ui_is_but_utf8(but)) {
2465                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
2466                         /* not a file?, strip non utf-8 chars */
2467                         if (strip) {
2468                                 /* wont happen often so isn't that annoying to keep it here for a while */
2469                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
2470                         }
2471                 }
2472                 
2473                 if (data->searchbox) {
2474                         if (data->cancel == false) {
2475                                 if ((ui_searchbox_apply(but, data->searchbox) == false) &&
2476                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
2477                                 {
2478                                         data->cancel = true;
2479                                 }
2480                         }
2481
2482                         ui_searchbox_free(C, data->searchbox);
2483                         data->searchbox = NULL;
2484                 }
2485                 
2486                 but->editstr = NULL;
2487                 but->pos = -1;
2488         }
2489         
2490         WM_cursor_modal_restore(CTX_wm_window(C));
2491 }
2492
2493 static void ui_textedit_next_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2494 {
2495         uiBut *but;
2496
2497         /* label and roundbox can overlap real buttons (backdrops...) */
2498         if (ELEM(actbut->type, LABEL, SEPR, SEPRLINE, ROUNDBOX, LISTBOX))
2499                 return;
2500
2501         for (but = actbut->next; but; but = but->next) {
2502                 if (ELEM(but->type, TEX, NUM, NUMSLI, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2503                         if (!(but->flag & UI_BUT_DISABLED)) {
2504                                 data->postbut = but;
2505                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2506                                 return;
2507                         }
2508                 }
2509         }
2510         for (but = block->buttons.first; but != actbut; but = but->next) {
2511                 if (ELEM(but->type, TEX, NUM, NUMSLI, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2512                         if (!(but->flag & UI_BUT_DISABLED)) {
2513                                 data->postbut = but;
2514                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2515                                 return;
2516                         }
2517                 }
2518         }
2519 }
2520
2521 static void ui_textedit_prev_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
2522 {
2523         uiBut *but;
2524
2525         /* label and roundbox can overlap real buttons (backdrops...) */
2526         if (ELEM(actbut->type, LABEL, SEPR, SEPRLINE, ROUNDBOX, LISTBOX))
2527                 return;
2528
2529         for (but = actbut->prev; but; but = but->prev) {
2530                 if (ELEM(but->type, TEX, NUM, NUMSLI, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2531                         if (!(but->flag & UI_BUT_DISABLED)) {
2532                                 data->postbut = but;
2533                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2534                                 return;
2535                         }
2536                 }
2537         }
2538         for (but = block->buttons.last; but != actbut; but = but->prev) {
2539                 if (ELEM(but->type, TEX, NUM, NUMSLI, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2540                         if (!(but->flag & UI_BUT_DISABLED)) {
2541                                 data->postbut = but;
2542                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
2543                                 return;
2544                         }
2545                 }
2546         }
2547 }
2548
2549
2550 static void ui_do_but_textedit(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2551 {
2552         int retval = WM_UI_HANDLER_CONTINUE;
2553         bool changed = false, inbox = false, update = false;
2554
2555         switch (event->type) {
2556                 case MOUSEMOVE:
2557                 case MOUSEPAN:
2558                         if (data->searchbox) {
2559 #ifdef USE_KEYNAV_LIMIT
2560                                 if ((event->type == MOUSEMOVE) && ui_mouse_motion_keynav_test(&data->searchbox_keynav_state, event)) {
2561                                         /* pass */
2562                                 }
2563                                 else {
2564                                         ui_searchbox_event(C, data->searchbox, but, event);
2565                                 }
2566 #else
2567                                 ui_searchbox_event(C, data->searchbox, but, event);
2568 #endif
2569                         }
2570                         
2571                         break;
2572                 case RIGHTMOUSE:
2573                 case ESCKEY:
2574                         if (event->val == KM_PRESS) {
2575                                 data->cancel = true;
2576                                 data->escapecancel = true;
2577                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2578                                 retval = WM_UI_HANDLER_BREAK;
2579                         }
2580                         break;
2581                 case LEFTMOUSE:
2582                 {
2583                         bool had_selection = but->selsta != but->selend;
2584                         
2585                         /* exit on LMB only on RELEASE for searchbox, to mimic other popups, and allow multiple menu levels */
2586                         if (data->searchbox)
2587                                 inbox = ui_searchbox_inside(data->searchbox, event->x, event->y);
2588
2589                         /* for double click: we do a press again for when you first click on button (selects all text, no cursor pos) */
2590                         if (event->val == KM_PRESS || event->val == KM_DBL_CLICK) {
2591                                 float mx, my;
2592
2593                                 mx = event->x;
2594                                 my = event->y;
2595                                 ui_window_to_block_fl(data->region, block, &mx, &my);
2596
2597                                 if (ui_but_contains_pt(but, mx, my)) {
2598                                         ui_textedit_set_cursor_pos(but, data, event->x);
2599                                         but->selsta = but->selend = but->pos;
2600                                         data->selstartx = event->x;
2601
2602                                         button_activate_state(C, but, BUTTON_STATE_TEXT_SELECTING);
2603                                         retval = WM_UI_HANDLER_BREAK;
2604                                 }
2605                                 else if (inbox == false) {
2606                                         /* if searchbox, click outside will cancel */
2607                                         if (data->searchbox)
2608                                                 data->cancel = data->escapecancel = true;
2609                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2610                                         retval = WM_UI_HANDLER_BREAK;
2611                                 }
2612                         }
2613                         
2614                         /* only select a word in button if there was no selection before */
2615                         if (event->val == KM_DBL_CLICK && had_selection == false) {
2616                                 ui_textedit_move(but, data, STRCUR_DIR_PREV, false, STRCUR_JUMP_DELIM);
2617                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT, true, STRCUR_JUMP_DELIM);
2618                                 retval = WM_UI_HANDLER_BREAK;
2619                                 changed = true;
2620                         }
2621                         else if (inbox) {
2622                                 /* if we allow activation on key press, it gives problems launching operators [#35713] */
2623                                 if (event->val == KM_RELEASE) {
2624                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2625                                         retval = WM_UI_HANDLER_BREAK;
2626                                 }
2627                         }
2628                         break;
2629                 }
2630         }
2631
2632         if (event->val == KM_PRESS) {
2633                 switch (event->type) {
2634                         case VKEY:
2635                         case XKEY:
2636                         case CKEY:
2637                                 if (event->ctrl || event->oskey) {
2638                                         if (event->type == VKEY)
2639                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_PASTE);
2640                                         else if (event->type == CKEY)
2641                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_COPY);
2642                                         else if (event->type == XKEY)
2643                                                 changed = ui_textedit_copypaste(but, data, UI_TEXTEDIT_CUT);
2644
2645                                         retval = WM_UI_HANDLER_BREAK;
2646                                 }
2647                                 break;
2648                         case RIGHTARROWKEY:
2649                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2650                                                  event->shift != 0, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2651                                 retval = WM_UI_HANDLER_BREAK;
2652                                 break;
2653                         case LEFTARROWKEY:
2654                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2655                                                  event->shift != 0, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2656                                 retval = WM_UI_HANDLER_BREAK;
2657                                 break;
2658                         case WHEELDOWNMOUSE:
2659                         case DOWNARROWKEY:
2660                                 if (data->searchbox) {
2661 #ifdef USE_KEYNAV_LIMIT
2662                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2663 #endif
2664                                         ui_searchbox_event(C, data->searchbox, but, event);
2665                                         break;
2666                                 }
2667                                 /* fall-through */
2668                         case ENDKEY:
2669                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2670                                                  event->shift != 0, STRCUR_JUMP_ALL);
2671                                 retval = WM_UI_HANDLER_BREAK;
2672                                 break;
2673                         case WHEELUPMOUSE:
2674                         case UPARROWKEY:
2675                                 if (data->searchbox) {
2676 #ifdef USE_KEYNAV_LIMIT
2677                                         ui_mouse_motion_keynav_init(&data->searchbox_keynav_state, event);
2678 #endif
2679                                         ui_searchbox_event(C, data->searchbox, but, event);
2680                                         break;
2681                                 }
2682                                 /* fall-through */
2683                         case HOMEKEY:
2684                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
2685                                                  event->shift != 0, STRCUR_JUMP_ALL);
2686                                 retval = WM_UI_HANDLER_BREAK;
2687                                 break;
2688                         case PADENTER:
2689                         case RETKEY:
2690                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2691                                 retval = WM_UI_HANDLER_BREAK;
2692                                 break;
2693                         case DELKEY:
2694                                 changed = ui_textedit_delete(but, data, 1,
2695                                                              event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2696                                 retval = WM_UI_HANDLER_BREAK;
2697                                 break;
2698
2699                         case BACKSPACEKEY:
2700                                 changed = ui_textedit_delete(but, data, 0,
2701                                                              event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
2702                                 retval = WM_UI_HANDLER_BREAK;
2703                                 break;
2704                                 
2705                         case AKEY:
2706
2707                                 /* Ctrl + A: Select all */
2708 #if defined(__APPLE__)
2709                                 /* OSX uses cmd-a systemwide, so add it */
2710                                 if ((event->oskey && !(event->alt || event->shift || event->ctrl)) ||
2711                                     (event->ctrl  && !(event->alt || event->shift || event->oskey)))
2712 #else
2713                                 if (event->ctrl && !(event->alt || event->shift || event->oskey))
2714 #endif
2715                                 {
2716                                         ui_textedit_move(but, data, STRCUR_DIR_PREV,
2717                                                          false, STRCUR_JUMP_ALL);
2718                                         ui_textedit_move(but, data, STRCUR_DIR_NEXT,
2719                                                          true, STRCUR_JUMP_ALL);
2720                                         retval = WM_UI_HANDLER_BREAK;
2721                                 }
2722                                 break;
2723
2724                         case TABKEY:
2725                                 /* there is a key conflict here, we can't tab with autocomplete */
2726                                 if (but->autocomplete_func || data->searchbox) {
2727                                         int autocomplete = ui_textedit_autocomplete(C, but, data);
2728                                         changed = autocomplete != AUTOCOMPLETE_NO_MATCH;
2729
2730                                         if (autocomplete == AUTOCOMPLETE_FULL_MATCH)
2731                                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2732
2733                                         update = true;  /* do live update for tab key */
2734                                 }
2735                                 /* the hotkey here is not well defined, was G.qual so we check all */
2736                                 else if (event->shift || event->ctrl || event->alt || event->oskey) {
2737                                         ui_textedit_prev_but(block, but, data);
2738                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2739                                 }
2740                                 else {
2741                                         ui_textedit_next_but(block, but, data);
2742                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2743                                 }
2744                                 retval = WM_UI_HANDLER_BREAK;
2745                                 break;
2746                 }
2747
2748                 if ((event->ascii || event->utf8_buf[0]) && (retval == WM_UI_HANDLER_CONTINUE)) {
2749                         char ascii = event->ascii;
2750                         const char *utf8_buf = event->utf8_buf;
2751
2752                         /* exception that's useful for number buttons, some keyboard
2753                          * numpads have a comma instead of a period */
2754                         if (ELEM(but->type, NUM, NUMSLI)) { /* could use data->min*/
2755                                 if (event->type == PADPERIOD && ascii == ',') {
2756                                         ascii = '.';
2757                                         utf8_buf = NULL; /* force ascii fallback */
2758                                 }
2759                         }
2760
2761                         if (utf8_buf && utf8_buf[0]) {
2762                                 int utf8_buf_len = BLI_str_utf8_size(utf8_buf);
2763                                 /* keep this printf until utf8 is well tested */
2764                                 if (utf8_buf_len != 1) {
2765                                         printf("%s: utf8 char '%.*s'\n", __func__, utf8_buf_len, utf8_buf);
2766                                 }
2767
2768                                 // strcpy(utf8_buf, "12345");
2769                                 changed = ui_textedit_type_buf(but, data, event->utf8_buf, utf8_buf_len);
2770                         }
2771                         else {
2772                                 changed = ui_textedit_type_ascii(but, data, ascii);
2773                         }
2774
2775                         retval = WM_UI_HANDLER_BREAK;
2776                         
2777                 }
2778                 /* textbutton with magnifier icon: do live update for search button */
2779                 if (but->icon == ICON_VIEWZOOM)
2780                         update = true;
2781         }
2782
2783         if (changed) {
2784                 /* only update when typing for TAB key */
2785                 if (update && data->interactive) {
2786                         ui_apply_button(C, block, but, data, true);
2787                 }
2788                 else {
2789                         ui_check_but(but);
2790                 }
2791                 but->changed = true;
2792                 
2793                 if (data->searchbox)
2794                         ui_searchbox_update(C, data->searchbox, but, true);  /* true = reset */
2795         }
2796
2797         if (changed || (retval == WM_UI_HANDLER_BREAK))
2798                 ED_region_tag_redraw(data->region);
2799 }
2800
2801 static void ui_do_but_textedit_select(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2802 {
2803         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2804
2805         switch (event->type) {
2806                 case MOUSEMOVE:
2807                 {
2808                         mx = event->x;
2809                         my = event->y;
2810                         ui_window_to_block(data->region, block, &mx, &my);
2811
2812                         ui_textedit_set_cursor_select(but, data, event->x);
2813                         retval = WM_UI_HANDLER_BREAK;
2814                         break;
2815                 }
2816                 case LEFTMOUSE:
2817                         if (event->val == KM_RELEASE)
2818                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2819                         retval = WM_UI_HANDLER_BREAK;
2820                         break;
2821         }
2822
2823         if (retval == WM_UI_HANDLER_BREAK) {
2824                 ui_check_but(but);
2825                 ED_region_tag_redraw(data->region);
2826         }
2827 }
2828
2829 /* ************* number editing for various types ************* */
2830
2831 static void ui_numedit_begin(uiBut *but, uiHandleButtonData *data)
2832 {
2833         if (but->type == BUT_CURVE) {
2834                 but->editcumap = (CurveMapping *)but->poin;
2835         }
2836         else if (but->type == BUT_COLORBAND) {
2837                 data->coba = (ColorBand *)but->poin;
2838                 but->editcoba = data->coba;
2839         }
2840         else if (ELEM(but->type, BUT_NORMAL, HSVCUBE, HSVCIRCLE, COLOR)) {
2841                 ui_get_but_vectorf(but, data->origvec);
2842                 copy_v3_v3(data->vec, data->origvec);
2843                 but->editvec = data->vec;
2844         }
2845         else {
2846                 float softrange, softmin, softmax;
2847
2848                 data->startvalue = ui_get_but_val(but);
2849                 data->origvalue = data->startvalue;
2850                 data->value = data->origvalue;
2851                 but->editval = &data->value;
2852
2853                 softmin = but->softmin;
2854                 softmax = but->softmax;
2855                 softrange = softmax - softmin;
2856
2857                 data->dragfstart = (softrange == 0.0f) ? 0.0f : ((float)data->value - softmin) / softrange;
2858                 data->dragf = data->dragfstart;
2859         }
2860
2861         data->dragchange = false;
2862         data->draglock = true;
2863 }
2864
2865 static void ui_numedit_end(uiBut *but, uiHandleButtonData *data)
2866 {
2867         but->editval = NULL;
2868         but->editvec = NULL;
2869         but->editcoba = NULL;
2870         but->editcumap = NULL;
2871
2872         data->dragstartx = 0;
2873         data->draglastx = 0;
2874         data->dragchange = false;
2875         data->dragcbd = NULL;
2876         data->dragsel = 0;
2877 }
2878
2879 static void ui_numedit_apply(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
2880 {
2881         if (data->interactive) {
2882                 ui_apply_button(C, block, but, data, true);
2883         }
2884         else {
2885                 ui_check_but(but);
2886         }
2887
2888         ED_region_tag_redraw(data->region);
2889 }
2890
2891 /* ****************** menu opening for various types **************** */
2892
2893 static void ui_blockopen_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2894 {
2895         uiBlockCreateFunc func = NULL;
2896         uiBlockHandleCreateFunc handlefunc = NULL;
2897         uiMenuCreateFunc menufunc = NULL;
2898         void *arg = NULL;
2899
2900         switch (but->type) {
2901                 case BLOCK:
2902                 case PULLDOWN:
2903                         if (but->menu_create_func) {
2904                                 menufunc = but->menu_create_func;
2905                                 arg = but->poin;
2906                         }
2907                         else {
2908                                 func = but->block_create_func;
2909                                 arg = but->poin ? but->poin : but->func_argN;
2910                         }
2911                         break;
2912                 case MENU:
2913                         BLI_assert(but->menu_create_func);
2914                         menufunc = but->menu_create_func;
2915                         arg = but->poin;
2916                         break;
2917                 case COLOR:
2918                         ui_get_but_vectorf(but, data->origvec);
2919                         copy_v3_v3(data->vec, data->origvec);
2920                         but->editvec = data->vec;
2921
2922                         handlefunc = ui_block_func_COLOR;
2923                         arg = but;
2924                         break;
2925
2926                         /* quiet warnings for unhandled types */
2927                 default:
2928                         break;
2929         }
2930
2931         if (func || handlefunc) {
2932                 data->menu = ui_popup_block_create(C, data->region, but, func, handlefunc, arg);
2933                 if (but->block->handle)
2934                         data->menu->popup = but->block->handle->popup;
2935         }
2936         else if (menufunc) {
2937                 data->menu = ui_popup_menu_create(C, data->region, but, menufunc, arg);
2938                 if (but->block->handle)
2939                         data->menu->popup = but->block->handle->popup;
2940         }
2941
2942         /* this makes adjacent blocks auto open from now on */
2943         //if (but->block->auto_open == 0) but->block->auto_open = 1;
2944 }
2945
2946 static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2947 {
2948         if (but) {
2949                 but->editval = NULL;
2950                 but->editvec = NULL;
2951
2952                 but->block->auto_open_last = PIL_check_seconds_timer();
2953         }
2954
2955         if (data->menu) {
2956                 ui_popup_block_free(C, data->menu);
2957                 data->menu = NULL;
2958         }
2959 }
2960
2961 int ui_button_open_menu_direction(uiBut *but)
2962 {
2963         uiHandleButtonData *data = but->active;
2964
2965         if (data && data->menu)
2966                 return data->menu->direction;
2967         
2968         return 0;
2969 }
2970
2971 /* Hack for uiList LISTROW buttons to "give" events to overlaying TEX buttons (cltr-clic rename feature & co). */
2972 static uiBut *ui_but_list_row_text_activate(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event,
2973                                             uiButtonActivateType activate_type)
2974 {
2975         ARegion *ar = CTX_wm_region(C);
2976         uiBut *labelbut = ui_but_find_mouse_over_ex(ar, event->x, event->y, true);
2977
2978         if (labelbut && labelbut->type == TEX && !(labelbut->flag & UI_BUT_DISABLED)) {
2979                 /* exit listrow */
2980                 data->cancel = true;
2981                 button_activate_exit(C, but, data, false, false);
2982
2983                 /* Activate the text button. */
2984                 button_activate_init(C, ar, labelbut, activate_type);
2985
2986                 return labelbut;
2987         }
2988         return NULL;
2989 }
2990
2991 /* ***************** events for different button types *************** */
2992
2993 static int ui_do_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
2994 {
2995         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2996                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2997                         button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE);
2998                         return WM_UI_HANDLER_BREAK;
2999                 }
3000                 else if (event->type == LEFTMOUSE && but->block->handle) {
3001                         /* regular buttons will be 'UI_SELECT', menu items 'UI_ACTIVE' */
3002                         if (!(but->flag & (UI_SELECT | UI_ACTIVE)))
3003                                 data->cancel = true;
3004                         button_activate_state(C, but, BUTTON_STATE_EXIT);
3005                         return WM_UI_HANDLER_BREAK;
3006                 }
3007                 else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
3008                         button_activate_state(C, but, BUTTON_STATE_WAIT_FLASH);
3009                         return WM_UI_HANDLER_BREAK;
3010                 }
3011         }
3012         else if (data->state == BUTTON_STATE_WAIT_RELEASE) {
3013                 if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
3014                         if (!(but->flag & UI_SELECT))
3015                                 data->cancel = true;
3016                         button_activate_state(C, but, BUTTON_STATE_EXIT);
3017                         return WM_UI_HANDLER_BREAK;
3018                 }
3019         }
3020
3021         return WM_UI_HANDLER_CONTINUE;
3022 }
3023
3024 static int ui_do_but_HOTKEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
3025 {
3026         if (data->state == BUTTON_STATE_HIGHLIGHT) {
3027                 if (ELEM(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
3028                         but->drawstr[0] = 0;
3029                         but->modifier_key = 0;
3030                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
3031         &nb