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