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