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