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