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