Purge gtk_widget_show from radiant/*
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "texwindow.h"
29
30 #include "debugging/debugging.h"
31 #include "warnings.h"
32
33 #include "ifilesystem.h"
34 #include "iundo.h"
35 #include "igl.h"
36 #include "iarchive.h"
37 #include "moduleobserver.h"
38
39 #include <set>
40 #include <string>
41 #include <vector>
42
43 #include <uilib/uilib.h>
44
45 #include "signal/signal.h"
46 #include "math/vector.h"
47 #include "texturelib.h"
48 #include "string/string.h"
49 #include "shaderlib.h"
50 #include "os/file.h"
51 #include "os/path.h"
52 #include "stream/memstream.h"
53 #include "stream/textfilestream.h"
54 #include "stream/stringstream.h"
55 #include "cmdlib.h"
56 #include "texmanip.h"
57 #include "textures.h"
58 #include "convert.h"
59
60 #include "gtkutil/menu.h"
61 #include "gtkutil/nonmodal.h"
62 #include "gtkutil/cursor.h"
63 #include "gtkutil/widget.h"
64 #include "gtkutil/glwidget.h"
65 #include "gtkutil/messagebox.h"
66
67 #include "error.h"
68 #include "map.h"
69 #include "qgl.h"
70 #include "select.h"
71 #include "brush_primit.h"
72 #include "brushmanip.h"
73 #include "patchmanip.h"
74 #include "plugin.h"
75 #include "qe3.h"
76 #include "gtkdlgs.h"
77 #include "gtkmisc.h"
78 #include "mainframe.h"
79 #include "findtexturedialog.h"
80 #include "surfacedialog.h"
81 #include "patchdialog.h"
82 #include "groupdialog.h"
83 #include "preferences.h"
84 #include "shaders.h"
85 #include "commands.h"
86
87 #define NOTEX_BASENAME "notex"
88 #define SHADERNOTEX_BASENAME "shadernotex"
89
90 bool TextureBrowser_showWads(){
91         return !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) );
92 }
93
94 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser );
95
96 bool string_equal_start( const char* string, StringRange start ){
97         return string_equal_n( string, start.first, start.last - start.first );
98 }
99
100 typedef std::set<CopiedString> TextureGroups;
101
102 void TextureGroups_addWad( TextureGroups& groups, const char* archive ){
103         if ( extension_equal( path_get_extension( archive ), "wad" ) ) {
104 #if 1
105                 groups.insert( archive );
106 #else
107                 CopiedString archiveBaseName( path_get_filename_start( archive ), path_get_filename_base_end( archive ) );
108                 groups.insert( archiveBaseName );
109 #endif
110         }
111 }
112 typedef ReferenceCaller1<TextureGroups, const char*, TextureGroups_addWad> TextureGroupsAddWadCaller;
113
114 namespace
115 {
116 bool g_TextureBrowser_shaderlistOnly = false;
117 bool g_TextureBrowser_fixedSize = true;
118 bool g_TextureBrowser_filterMissing = false;
119 bool g_TextureBrowser_filterFallback = true;
120 bool g_TextureBrowser_enableAlpha = true;
121 }
122
123 CopiedString g_notex;
124 CopiedString g_shadernotex;
125 bool isMissing(const char* name);
126 bool isNotex(const char* name);
127
128 bool isMissing(const char* name){
129         if ( string_equal( g_notex.c_str(), name ) ) {
130                 return true;
131         }
132         if ( string_equal( g_shadernotex.c_str(), name ) ) {
133                 return true;
134         }
135         return false;
136 }
137
138 bool isNotex(const char* name){
139         if ( string_equal_suffix( name, "/" NOTEX_BASENAME ) ) {
140                 return true;
141         }
142         if ( string_equal_suffix( name, "/" SHADERNOTEX_BASENAME ) ) {
143                 return true;
144         }
145         return false;
146 }
147
148 void TextureGroups_addShader( TextureGroups& groups, const char* shaderName ){
149         const char* texture = path_make_relative( shaderName, "textures/" );
150
151         // hide notex / shadernotex images
152         if ( g_TextureBrowser_filterFallback ) {
153                 if ( isNotex( shaderName ) ) {
154                         return;
155                 }
156                 if ( isNotex( texture ) ) {
157                         return;
158                 }
159         }
160
161         if ( texture != shaderName ) {
162                 const char* last = path_remove_directory( texture );
163                 if ( !string_empty( last ) ) {
164                         groups.insert( CopiedString( StringRange( texture, --last ) ) );
165                 }
166         }
167 }
168 typedef ReferenceCaller1<TextureGroups, const char*, TextureGroups_addShader> TextureGroupsAddShaderCaller;
169
170 void TextureGroups_addDirectory( TextureGroups& groups, const char* directory ){
171         groups.insert( directory );
172 }
173 typedef ReferenceCaller1<TextureGroups, const char*, TextureGroups_addDirectory> TextureGroupsAddDirectoryCaller;
174
175 class DeferredAdjustment
176 {
177 gdouble m_value;
178 guint m_handler;
179 typedef void ( *ValueChangedFunction )( void* data, gdouble value );
180 ValueChangedFunction m_function;
181 void* m_data;
182
183 static gboolean deferred_value_changed( gpointer data ){
184         reinterpret_cast<DeferredAdjustment*>( data )->m_function(
185                 reinterpret_cast<DeferredAdjustment*>( data )->m_data,
186                 reinterpret_cast<DeferredAdjustment*>( data )->m_value
187                 );
188         reinterpret_cast<DeferredAdjustment*>( data )->m_handler = 0;
189         reinterpret_cast<DeferredAdjustment*>( data )->m_value = 0;
190         return FALSE;
191 }
192 public:
193 DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){
194 }
195 void flush(){
196         if ( m_handler != 0 ) {
197                 g_source_remove( m_handler );
198                 deferred_value_changed( this );
199         }
200 }
201 void value_changed( gdouble value ){
202         m_value = value;
203         if ( m_handler == 0 ) {
204                 m_handler = g_idle_add( deferred_value_changed, this );
205         }
206 }
207 static void adjustment_value_changed( GtkAdjustment *adjustment, DeferredAdjustment* self ){
208         self->value_changed( gtk_adjustment_get_value(adjustment) );
209 }
210 };
211
212
213
214 class TextureBrowser;
215
216 typedef ReferenceCaller<TextureBrowser, TextureBrowser_queueDraw> TextureBrowserQueueDrawCaller;
217
218 void TextureBrowser_scrollChanged( void* data, gdouble value );
219
220
221 enum StartupShaders
222 {
223         STARTUPSHADERS_NONE = 0,
224         STARTUPSHADERS_COMMON,
225 };
226
227 void TextureBrowser_hideUnusedExport( const BoolImportCallback& importer );
228 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
229
230 void TextureBrowser_showShadersExport( const BoolImportCallback& importer );
231 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
232
233 void TextureBrowser_showShaderlistOnly( const BoolImportCallback& importer );
234 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
235
236 void TextureBrowser_fixedSize( const BoolImportCallback& importer );
237 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_fixedSize> TextureBrowserFixedSizeExport;
238
239 void TextureBrowser_filterMissing( const BoolImportCallback& importer );
240 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_filterMissing> TextureBrowserFilterMissingExport;
241
242 void TextureBrowser_filterFallback( const BoolImportCallback& importer );
243 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_filterFallback> TextureBrowserFilterFallbackExport;
244
245 void TextureBrowser_enableAlpha( const BoolImportCallback& importer );
246 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_enableAlpha> TextureBrowserEnableAlphaExport;
247
248 class TextureBrowser
249 {
250 public:
251 int width, height;
252 int originy;
253 int m_nTotalHeight;
254
255 CopiedString shader;
256
257 ui::Window m_parent;
258 ui::Widget m_gl_widget;
259 ui::Widget m_texture_scroll;
260 ui::Widget m_treeViewTree;
261 ui::Widget m_treeViewTags;
262 ui::Widget m_tag_frame;
263 ui::ListStore m_assigned_store{nullptr};
264 ui::ListStore m_available_store{nullptr};
265 ui::Widget m_assigned_tree;
266 ui::Widget m_available_tree;
267 ui::Widget m_scr_win_tree;
268 ui::Widget m_scr_win_tags;
269 ui::Widget m_tag_notebook;
270 ui::Widget m_search_button;
271 ui::Widget m_shader_info_item;
272
273 std::set<CopiedString> m_all_tags;
274 ui::ListStore m_all_tags_list{nullptr};
275 std::vector<CopiedString> m_copied_tags;
276 std::set<CopiedString> m_found_shaders;
277
278 ToggleItem m_hideunused_item;
279 ToggleItem m_hidenotex_item;
280 ToggleItem m_showshaders_item;
281 ToggleItem m_showshaderlistonly_item;
282 ToggleItem m_fixedsize_item;
283 ToggleItem m_filternotex_item;
284 ToggleItem m_enablealpha_item;
285
286 guint m_sizeHandler;
287 guint m_exposeHandler;
288
289 bool m_heightChanged;
290 bool m_originInvalid;
291
292 DeferredAdjustment m_scrollAdjustment;
293 FreezePointer m_freezePointer;
294
295 Vector3 color_textureback;
296 // the increment step we use against the wheel mouse
297 std::size_t m_mouseWheelScrollIncrement;
298 std::size_t m_textureScale;
299 // make the texture increments match the grid changes
300 bool m_showShaders;
301 bool m_showTextureScrollbar;
302 StartupShaders m_startupShaders;
303 // if true, the texture window will only display in-use shaders
304 // if false, all the shaders in memory are displayed
305 bool m_hideUnused;
306 bool m_rmbSelected;
307 bool m_searchedTags;
308 bool m_tags;
309 // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true.
310 int m_uniformTextureSize;
311 // Return the display width of a texture in the texture browser
312 int getTextureWidth( qtexture_t* tex ){
313         int width;
314         if ( !g_TextureBrowser_fixedSize ) {
315                 // Don't use uniform size
316                 width = (int)( tex->width * ( (float)m_textureScale / 100 ) );
317         }
318         else if
319         ( tex->width >= tex->height ) {
320                 // Texture is square, or wider than it is tall
321                 width = m_uniformTextureSize;
322         }
323         else {
324                 // Otherwise, preserve the texture's aspect ratio
325                 width = (int)( m_uniformTextureSize * ( (float)tex->width / tex->height ) );
326         }
327         return width;
328 }
329 // Return the display height of a texture in the texture browser
330 int getTextureHeight( qtexture_t* tex ){
331         int height;
332         if ( !g_TextureBrowser_fixedSize ) {
333                 // Don't use uniform size
334                 height = (int)( tex->height * ( (float)m_textureScale / 100 ) );
335         }
336         else if ( tex->height >= tex->width ) {
337                 // Texture is square, or taller than it is wide
338                 height = m_uniformTextureSize;
339         }
340         else {
341                 // Otherwise, preserve the texture's aspect ratio
342                 height = (int)( m_uniformTextureSize * ( (float)tex->height / tex->width ) );
343         }
344         return height;
345 }
346
347 TextureBrowser() :
348         m_texture_scroll( 0 ),
349         m_hideunused_item( TextureBrowserHideUnusedExport() ),
350         m_showshaders_item( TextureBrowserShowShadersExport() ),
351         m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ),
352         m_fixedsize_item( TextureBrowserFixedSizeExport() ),
353         m_filternotex_item( TextureBrowserFilterMissingExport() ),
354         m_hidenotex_item( TextureBrowserFilterFallbackExport() ),
355         m_enablealpha_item( TextureBrowserEnableAlphaExport() ),
356         m_heightChanged( true ),
357         m_originInvalid( true ),
358         m_scrollAdjustment( TextureBrowser_scrollChanged, this ),
359         color_textureback( 0.25f, 0.25f, 0.25f ),
360         m_mouseWheelScrollIncrement( 64 ),
361         m_textureScale( 50 ),
362         m_showShaders( true ),
363         m_showTextureScrollbar( true ),
364         m_startupShaders( STARTUPSHADERS_NONE ),
365         m_hideUnused( false ),
366         m_rmbSelected( false ),
367         m_searchedTags( false ),
368         m_tags( false ),
369         m_uniformTextureSize( 96 ){
370 }
371 };
372
373 void ( *TextureBrowser_textureSelected )( const char* shader );
374
375
376 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser );
377
378
379 const char* TextureBrowser_getComonShadersName(){
380         const char* value = g_pGameDescription->getKeyValue( "common_shaders_name" );
381         if ( !string_empty( value ) ) {
382                 return value;
383         }
384         return "Common";
385 }
386
387 const char* TextureBrowser_getComonShadersDir(){
388         const char* value = g_pGameDescription->getKeyValue( "common_shaders_dir" );
389         if ( !string_empty( value ) ) {
390                 return value;
391         }
392         return "common/";
393 }
394
395 inline int TextureBrowser_fontHeight( TextureBrowser& textureBrowser ){
396         return GlobalOpenGL().m_font->getPixelHeight();
397 }
398
399 const char* TextureBrowser_GetSelectedShader( TextureBrowser& textureBrowser ){
400         return textureBrowser.shader.c_str();
401 }
402
403 void TextureBrowser_SetStatus( TextureBrowser& textureBrowser, const char* name ){
404         IShader* shader = QERApp_Shader_ForName( name );
405         qtexture_t* q = shader->getTexture();
406         StringOutputStream strTex( 256 );
407         strTex << name << " W: " << Unsigned( q->width ) << " H: " << Unsigned( q->height );
408         shader->DecRef();
409         g_pParentWnd->SetStatusText( g_pParentWnd->m_texture_status, strTex.c_str() );
410 }
411
412 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name );
413
414 void TextureBrowser_SetSelectedShader( TextureBrowser& textureBrowser, const char* shader ){
415         textureBrowser.shader = shader;
416         TextureBrowser_SetStatus( textureBrowser, shader );
417         TextureBrowser_Focus( textureBrowser, shader );
418
419         if ( FindTextureDialog_isOpen() ) {
420                 FindTextureDialog_selectTexture( shader );
421         }
422
423         // disable the menu item "shader info" if no shader was selected
424         IShader* ishader = QERApp_Shader_ForName( shader );
425         CopiedString filename = ishader->getShaderFileName();
426
427         if ( filename.empty() ) {
428                 if ( textureBrowser.m_shader_info_item != NULL ) {
429                         gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
430                 }
431         }
432         else {
433                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, TRUE );
434         }
435
436         ishader->DecRef();
437 }
438
439
440 CopiedString g_TextureBrowser_currentDirectory;
441
442 /*
443    ============================================================================
444
445    TEXTURE LAYOUT
446
447    TTimo: now based on a rundown through all the shaders
448    NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
449    otherwise we may need to rely on a list instead of an array storage
450    ============================================================================
451  */
452
453 class TextureLayout
454 {
455 public:
456 // texture layout functions
457 // TTimo: now based on shaders
458 int current_x, current_y, current_row;
459 };
460
461 void Texture_StartPos( TextureLayout& layout ){
462         layout.current_x = 8;
463         layout.current_y = -8;
464         layout.current_row = 0;
465 }
466
467 void Texture_NextPos( TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y ){
468         qtexture_t* q = current_texture;
469
470         int nWidth = textureBrowser.getTextureWidth( q );
471         int nHeight = textureBrowser.getTextureHeight( q );
472         if ( layout.current_x + nWidth > textureBrowser.width - 8 && layout.current_row ) { // go to the next row unless the texture is the first on the row
473                 layout.current_x = 8;
474                 layout.current_y -= layout.current_row + TextureBrowser_fontHeight( textureBrowser ) + 4;
475                 layout.current_row = 0;
476         }
477
478         *x = layout.current_x;
479         *y = layout.current_y;
480
481         // Is our texture larger than the row? If so, grow the
482         // row height to match it
483
484         if ( layout.current_row < nHeight ) {
485                 layout.current_row = nHeight;
486         }
487
488         // never go less than 96, or the names get all crunched up
489         layout.current_x += nWidth < 96 ? 96 : nWidth;
490         layout.current_x += 8;
491 }
492
493 bool TextureSearch_IsShown( const char* name ){
494         std::set<CopiedString>::iterator iter;
495
496         iter = GlobalTextureBrowser().m_found_shaders.find( name );
497
498         if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
499                 return false;
500         }
501         else {
502                 return true;
503         }
504 }
505
506 // if texture_showinuse jump over non in-use textures
507 bool Texture_IsShown( IShader* shader, bool show_shaders, bool hideUnused ){
508         // filter missing shaders
509         // ugly: filter on built-in fallback name after substitution
510         if ( g_TextureBrowser_filterMissing ) {
511                 if ( isMissing( shader->getTexture()->name ) ) {
512                         return false;
513                 }
514         }
515         // filter the fallback (notex/shadernotex) for missing shaders or editor image
516         if ( g_TextureBrowser_filterFallback ) {
517                 if ( isNotex( shader->getName() ) ) {
518                         return false;
519                 }
520                 if ( isNotex( shader->getTexture()->name ) ) {
521                         return false;
522                 }
523         }
524
525         if ( g_TextureBrowser_currentDirectory == "Untagged" ) {
526                 std::set<CopiedString>::iterator iter;
527
528                 iter = GlobalTextureBrowser().m_found_shaders.find( shader->getName() );
529
530                 if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
531                         return false;
532                 }
533                 else {
534                         return true;
535                 }
536         }
537
538         if ( !shader_equal_prefix( shader->getName(), "textures/" ) ) {
539                 return false;
540         }
541
542         if ( !show_shaders && !shader->IsDefault() ) {
543                 return false;
544         }
545
546         if ( hideUnused && !shader->IsInUse() ) {
547                 return false;
548         }
549
550         if ( GlobalTextureBrowser().m_searchedTags ) {
551                 if ( !TextureSearch_IsShown( shader->getName() ) ) {
552                         return false;
553                 }
554                 else {
555                         return true;
556                 }
557         }
558         else {
559                 if ( !shader_equal_prefix( shader_get_textureName( shader->getName() ), g_TextureBrowser_currentDirectory.c_str() ) ) {
560                         return false;
561                 }
562         }
563
564         return true;
565 }
566
567 void TextureBrowser_heightChanged( TextureBrowser& textureBrowser ){
568         textureBrowser.m_heightChanged = true;
569
570         TextureBrowser_updateScroll( textureBrowser );
571         TextureBrowser_queueDraw( textureBrowser );
572 }
573
574 void TextureBrowser_evaluateHeight( TextureBrowser& textureBrowser ){
575         if ( textureBrowser.m_heightChanged ) {
576                 textureBrowser.m_heightChanged = false;
577
578                 textureBrowser.m_nTotalHeight = 0;
579
580                 TextureLayout layout;
581                 Texture_StartPos( layout );
582                 for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
583                 {
584                         IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
585
586                         if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
587                                 continue;
588                         }
589
590                         int x, y;
591                         Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
592                         textureBrowser.m_nTotalHeight = std::max( textureBrowser.m_nTotalHeight, abs( layout.current_y ) + TextureBrowser_fontHeight( textureBrowser ) + textureBrowser.getTextureHeight( shader->getTexture() ) + 4 );
593                 }
594         }
595 }
596
597 int TextureBrowser_TotalHeight( TextureBrowser& textureBrowser ){
598         TextureBrowser_evaluateHeight( textureBrowser );
599         return textureBrowser.m_nTotalHeight;
600 }
601
602 inline const int& min_int( const int& left, const int& right ){
603         return std::min( left, right );
604 }
605
606 void TextureBrowser_clampOriginY( TextureBrowser& textureBrowser ){
607         if ( textureBrowser.originy > 0 ) {
608                 textureBrowser.originy = 0;
609         }
610         int lower = min_int( textureBrowser.height - TextureBrowser_TotalHeight( textureBrowser ), 0 );
611         if ( textureBrowser.originy < lower ) {
612                 textureBrowser.originy = lower;
613         }
614 }
615
616 int TextureBrowser_getOriginY( TextureBrowser& textureBrowser ){
617         if ( textureBrowser.m_originInvalid ) {
618                 textureBrowser.m_originInvalid = false;
619                 TextureBrowser_clampOriginY( textureBrowser );
620                 TextureBrowser_updateScroll( textureBrowser );
621         }
622         return textureBrowser.originy;
623 }
624
625 void TextureBrowser_setOriginY( TextureBrowser& textureBrowser, int originy ){
626         textureBrowser.originy = originy;
627         TextureBrowser_clampOriginY( textureBrowser );
628         TextureBrowser_updateScroll( textureBrowser );
629         TextureBrowser_queueDraw( textureBrowser );
630 }
631
632
633 Signal0 g_activeShadersChangedCallbacks;
634
635 void TextureBrowser_addActiveShadersChangedCallback( const SignalHandler& handler ){
636         g_activeShadersChangedCallbacks.connectLast( handler );
637 }
638
639 void TextureBrowser_constructTreeStore();
640
641 class ShadersObserver : public ModuleObserver
642 {
643 Signal0 m_realiseCallbacks;
644 public:
645 void realise(){
646         m_realiseCallbacks();
647         TextureBrowser_constructTreeStore();
648 }
649 void unrealise(){
650 }
651 void insert( const SignalHandler& handler ){
652         m_realiseCallbacks.connectLast( handler );
653 }
654 };
655
656 namespace
657 {
658 ShadersObserver g_ShadersObserver;
659 }
660
661 void TextureBrowser_addShadersRealiseCallback( const SignalHandler& handler ){
662         g_ShadersObserver.insert( handler );
663 }
664
665 void TextureBrowser_activeShadersChanged( TextureBrowser& textureBrowser ){
666         TextureBrowser_heightChanged( textureBrowser );
667         textureBrowser.m_originInvalid = true;
668
669         g_activeShadersChangedCallbacks();
670 }
671
672 void TextureBrowser_importShowScrollbar( TextureBrowser& textureBrowser, bool value ){
673         textureBrowser.m_showTextureScrollbar = value;
674         if ( textureBrowser.m_texture_scroll != 0 ) {
675                 widget_set_visible( textureBrowser.m_texture_scroll, textureBrowser.m_showTextureScrollbar );
676                 TextureBrowser_updateScroll( textureBrowser );
677         }
678 }
679 typedef ReferenceCaller1<TextureBrowser, bool, TextureBrowser_importShowScrollbar> TextureBrowserImportShowScrollbarCaller;
680
681
682 /*
683    ==============
684    TextureBrowser_ShowDirectory
685    relies on texture_directory global for the directory to use
686    1) Load the shaders for the given directory
687    2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
688    NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
689    available through the IShaders interface
690    NOTE: for texture window layout:
691    all shaders are stored with alphabetical order after load
692    previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
693    ( the GL textures are not flushed though)
694    ==============
695  */
696
697 bool endswith( const char *haystack, const char *needle ){
698         size_t lh = strlen( haystack );
699         size_t ln = strlen( needle );
700         if ( lh < ln ) {
701                 return false;
702         }
703         return !memcmp( haystack + ( lh - ln ), needle, ln );
704 }
705
706 bool texture_name_ignore( const char* name ){
707         StringOutputStream strTemp( string_length( name ) );
708         strTemp << LowerCase( name );
709
710         return
711                 endswith( strTemp.c_str(), ".specular" ) ||
712                 endswith( strTemp.c_str(), ".glow" ) ||
713                 endswith( strTemp.c_str(), ".bump" ) ||
714                 endswith( strTemp.c_str(), ".diffuse" ) ||
715                 endswith( strTemp.c_str(), ".blend" ) ||
716                 endswith( strTemp.c_str(), ".alpha" ) ||
717                 endswith( strTemp.c_str(), "_norm" ) ||
718                 endswith( strTemp.c_str(), "_bump" ) ||
719                 endswith( strTemp.c_str(), "_glow" ) ||
720                 endswith( strTemp.c_str(), "_gloss" ) ||
721                 endswith( strTemp.c_str(), "_pants" ) ||
722                 endswith( strTemp.c_str(), "_shirt" ) ||
723                 endswith( strTemp.c_str(), "_reflect" ) ||
724                 endswith( strTemp.c_str(), "_alpha" ) ||
725                 0;
726 }
727
728 class LoadShaderVisitor : public Archive::Visitor
729 {
730 public:
731 void visit( const char* name ){
732         IShader* shader = QERApp_Shader_ForName( CopiedString( StringRange( name, path_get_filename_base_end( name ) ) ).c_str() );
733         shader->DecRef();
734 }
735 };
736
737 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused );
738
739 ui::Widget g_page_textures;
740
741 void TextureBrowser_toggleShow(){
742         GroupDialog_showPage( g_page_textures );
743 }
744
745
746 void TextureBrowser_updateTitle(){
747         GroupDialog_updatePageTitle( g_page_textures );
748 }
749
750
751
752 class TextureCategoryLoadShader
753 {
754 const char* m_directory;
755 std::size_t& m_count;
756 public:
757 typedef const char* first_argument_type;
758
759 TextureCategoryLoadShader( const char* directory, std::size_t& count )
760         : m_directory( directory ), m_count( count ){
761         m_count = 0;
762 }
763 void operator()( const char* name ) const {
764         if ( shader_equal_prefix( name, "textures/" )
765                  && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) {
766                 ++m_count;
767                 // request the shader, this will load the texture if needed
768                 // this Shader_ForName call is a kind of hack
769                 IShader *pFoo = QERApp_Shader_ForName( name );
770                 pFoo->DecRef();
771         }
772 }
773 };
774
775 void TextureDirectory_loadTexture( const char* directory, const char* texture ){
776         StringOutputStream name( 256 );
777         name << directory << StringRange( texture, path_get_filename_base_end( texture ) );
778
779         if ( texture_name_ignore( name.c_str() ) ) {
780                 return;
781         }
782
783         if ( !shader_valid( name.c_str() ) ) {
784                 globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n";
785                 return;
786         }
787
788         // if a texture is already in use to represent a shader, ignore it
789         IShader* shader = QERApp_Shader_ForName( name.c_str() );
790         shader->DecRef();
791 }
792 typedef ConstPointerCaller1<char, const char*, TextureDirectory_loadTexture> TextureDirectoryLoadTextureCaller;
793
794 class LoadTexturesByTypeVisitor : public ImageModules::Visitor
795 {
796 const char* m_dirstring;
797 public:
798 LoadTexturesByTypeVisitor( const char* dirstring )
799         : m_dirstring( dirstring ){
800 }
801 void visit( const char* minor, const _QERPlugImageTable& table ) const {
802         GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) );
803 }
804 };
805
806 void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){
807         if ( TextureBrowser_showWads() ) {
808                 Archive* archive = GlobalFileSystem().getArchive( directory );
809                 ASSERT_NOTNULL( archive );
810                 LoadShaderVisitor visitor;
811                 archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "textures/" );
812         }
813         else
814         {
815                 g_TextureBrowser_currentDirectory = directory;
816                 TextureBrowser_heightChanged( textureBrowser );
817
818                 std::size_t shaders_count;
819                 GlobalShaderSystem().foreachShaderName( makeCallback1( TextureCategoryLoadShader( directory, shaders_count ) ) );
820                 globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
821
822                 if ( g_pGameDescription->mGameType != "doom3" ) {
823                         // load remaining texture files
824
825                         StringOutputStream dirstring( 64 );
826                         dirstring << "textures/" << directory;
827
828                         Radiant_getImageModules().foreachModule( LoadTexturesByTypeVisitor( dirstring.c_str() ) );
829                 }
830         }
831
832         // we'll display the newly loaded textures + all the ones already in use
833         TextureBrowser_SetHideUnused( textureBrowser, false );
834
835         TextureBrowser_updateTitle();
836 }
837
838 void TextureBrowser_ShowTagSearchResult( TextureBrowser& textureBrowser, const char* directory ){
839         g_TextureBrowser_currentDirectory = directory;
840         TextureBrowser_heightChanged( textureBrowser );
841
842         std::size_t shaders_count;
843         GlobalShaderSystem().foreachShaderName( makeCallback1( TextureCategoryLoadShader( directory, shaders_count ) ) );
844         globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
845
846         if ( g_pGameDescription->mGameType != "doom3" ) {
847                 // load remaining texture files
848                 StringOutputStream dirstring( 64 );
849                 dirstring << "textures/" << directory;
850
851                 {
852                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
853                         Radiant_getImageModules().foreachModule( visitor );
854                 }
855         }
856
857         // we'll display the newly loaded textures + all the ones already in use
858         TextureBrowser_SetHideUnused( textureBrowser, false );
859 }
860
861
862 bool TextureBrowser_hideUnused();
863
864 void TextureBrowser_hideUnusedExport( const BoolImportCallback& importer ){
865         importer( TextureBrowser_hideUnused() );
866 }
867 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
868
869 void TextureBrowser_showShadersExport( const BoolImportCallback& importer ){
870         importer( GlobalTextureBrowser().m_showShaders );
871 }
872 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
873
874 void TextureBrowser_showShaderlistOnly( const BoolImportCallback& importer ){
875         importer( g_TextureBrowser_shaderlistOnly );
876 }
877 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
878
879 void TextureBrowser_fixedSize( const BoolImportCallback& importer ){
880         importer( g_TextureBrowser_fixedSize );
881 }
882 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_fixedSize> TextureBrowser_FixedSizeExport;
883
884 void TextureBrowser_filterMissing( const BoolImportCallback& importer ){
885         importer( g_TextureBrowser_filterMissing );
886 }
887 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_filterMissing> TextureBrowser_filterMissingExport;
888
889 void TextureBrowser_filterFallback( const BoolImportCallback& importer ){
890         importer( g_TextureBrowser_filterFallback );
891 }
892 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_filterFallback> TextureBrowser_filterFallbackExport;
893
894 void TextureBrowser_enableAlpha( const BoolImportCallback& importer ){
895         importer( g_TextureBrowser_enableAlpha );
896 }
897 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_enableAlpha> TextureBrowser_enableAlphaExport;
898
899 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ){
900         if ( hideUnused ) {
901                 textureBrowser.m_hideUnused = true;
902         }
903         else
904         {
905                 textureBrowser.m_hideUnused = false;
906         }
907
908         textureBrowser.m_hideunused_item.update();
909
910         TextureBrowser_heightChanged( textureBrowser );
911         textureBrowser.m_originInvalid = true;
912 }
913
914 void TextureBrowser_ShowStartupShaders( TextureBrowser& textureBrowser ){
915         if ( textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON ) {
916                 TextureBrowser_ShowDirectory( textureBrowser, TextureBrowser_getComonShadersDir() );
917         }
918 }
919
920
921 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
922 // it might need to be split in parts or moved out .. dunno
923 // scroll origin so the specified texture is completely on screen
924 // if current texture is not displayed, nothing is changed
925 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name ){
926         TextureLayout layout;
927         // scroll origin so the texture is completely on screen
928         Texture_StartPos( layout );
929
930         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
931         {
932                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
933
934                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
935                         continue;
936                 }
937
938                 int x, y;
939                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
940                 qtexture_t* q = shader->getTexture();
941                 if ( !q ) {
942                         break;
943                 }
944
945                 // we have found when texdef->name and the shader name match
946                 // NOTE: as everywhere else for our comparisons, we are not case sensitive
947                 if ( shader_equal( name, shader->getName() ) ) {
948                         int textureHeight = (int)( q->height * ( (float)textureBrowser.m_textureScale / 100 ) )
949                                                                 + 2 * TextureBrowser_fontHeight( textureBrowser );
950
951                         int originy = TextureBrowser_getOriginY( textureBrowser );
952                         if ( y > originy ) {
953                                 originy = y;
954                         }
955
956                         if ( y - textureHeight < originy - textureBrowser.height ) {
957                                 originy = ( y - textureHeight ) + textureBrowser.height;
958                         }
959
960                         TextureBrowser_setOriginY( textureBrowser, originy );
961                         return;
962                 }
963         }
964 }
965
966 IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){
967         my += TextureBrowser_getOriginY( textureBrowser ) - textureBrowser.height;
968
969         TextureLayout layout;
970         Texture_StartPos( layout );
971         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
972         {
973                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
974
975                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
976                         continue;
977                 }
978
979                 int x, y;
980                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
981                 qtexture_t  *q = shader->getTexture();
982                 if ( !q ) {
983                         break;
984                 }
985
986                 int nWidth = textureBrowser.getTextureWidth( q );
987                 int nHeight = textureBrowser.getTextureHeight( q );
988                 if ( mx > x && mx - x < nWidth
989                          && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) {
990                         return shader;
991                 }
992         }
993
994         return 0;
995 }
996
997 /*
998    ==============
999    SelectTexture
1000
1001    By mouse click
1002    ==============
1003  */
1004 void SelectTexture( TextureBrowser& textureBrowser, int mx, int my, bool bShift ){
1005         IShader* shader = Texture_At( textureBrowser, mx, my );
1006         if ( shader != 0 ) {
1007                 if ( bShift ) {
1008                         if ( shader->IsDefault() ) {
1009                                 globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n";
1010                         }
1011                         else{
1012                                 ViewShader( shader->getShaderFileName(), shader->getName() );
1013                         }
1014                 }
1015                 else
1016                 {
1017                         TextureBrowser_SetSelectedShader( textureBrowser, shader->getName() );
1018                         TextureBrowser_textureSelected( shader->getName() );
1019
1020                         if ( !FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected ) {
1021                                 UndoableCommand undo( "textureNameSetSelected" );
1022                                 Select_SetShader( shader->getName() );
1023                         }
1024                 }
1025         }
1026 }
1027
1028 /*
1029    ============================================================================
1030
1031    MOUSE ACTIONS
1032
1033    ============================================================================
1034  */
1035
1036 void TextureBrowser_trackingDelta( int x, int y, unsigned int state, void* data ){
1037         TextureBrowser& textureBrowser = *reinterpret_cast<TextureBrowser*>( data );
1038         if ( y != 0 ) {
1039                 int scale = 1;
1040
1041                 if ( state & GDK_SHIFT_MASK ) {
1042                         scale = 4;
1043                 }
1044
1045                 int originy = TextureBrowser_getOriginY( textureBrowser );
1046                 originy += y * scale;
1047                 TextureBrowser_setOriginY( textureBrowser, originy );
1048         }
1049 }
1050
1051 void TextureBrowser_Tracking_MouseDown( TextureBrowser& textureBrowser ){
1052         textureBrowser.m_freezePointer.freeze_pointer( textureBrowser.m_parent, TextureBrowser_trackingDelta, &textureBrowser );
1053 }
1054
1055 void TextureBrowser_Tracking_MouseUp( TextureBrowser& textureBrowser ){
1056         textureBrowser.m_freezePointer.unfreeze_pointer( textureBrowser.m_parent );
1057 }
1058
1059 void TextureBrowser_Selection_MouseDown( TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy ){
1060         SelectTexture( textureBrowser, pointx, textureBrowser.height - 1 - pointy, ( flags & GDK_SHIFT_MASK ) != 0 );
1061 }
1062
1063 /*
1064    ============================================================================
1065
1066    DRAWING
1067
1068    ============================================================================
1069  */
1070
1071 /*
1072    ============
1073    Texture_Draw
1074    TTimo: relying on the shaders list to display the textures
1075    we must query all qtexture_t* to manage and display through the IShaders interface
1076    this allows a plugin to completely override the texture system
1077    ============
1078  */
1079 void Texture_Draw( TextureBrowser& textureBrowser ){
1080         int originy = TextureBrowser_getOriginY( textureBrowser );
1081
1082         glClearColor( textureBrowser.color_textureback[0],
1083                                   textureBrowser.color_textureback[1],
1084                                   textureBrowser.color_textureback[2],
1085                                   0 );
1086         glViewport( 0, 0, textureBrowser.width, textureBrowser.height );
1087         glMatrixMode( GL_PROJECTION );
1088         glLoadIdentity();
1089
1090         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1091         glDisable( GL_DEPTH_TEST );
1092         if ( g_TextureBrowser_enableAlpha ) {
1093                 glEnable( GL_BLEND );
1094                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1095         }
1096         else {
1097                 glDisable( GL_BLEND );
1098         }
1099         glOrtho( 0, textureBrowser.width, originy - textureBrowser.height, originy, -100, 100 );
1100         glEnable( GL_TEXTURE_2D );
1101
1102         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1103
1104         int last_y = 0, last_height = 0;
1105
1106         TextureLayout layout;
1107         Texture_StartPos( layout );
1108         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1109         {
1110                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1111
1112                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
1113                         continue;
1114                 }
1115
1116                 int x, y;
1117                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1118                 qtexture_t *q = shader->getTexture();
1119                 if ( !q ) {
1120                         break;
1121                 }
1122
1123                 int nWidth = textureBrowser.getTextureWidth( q );
1124                 int nHeight = textureBrowser.getTextureHeight( q );
1125
1126                 if ( y != last_y ) {
1127                         last_y = y;
1128                         last_height = 0;
1129                 }
1130                 last_height = std::max( nHeight, last_height );
1131
1132                 // Is this texture visible?
1133                 if ( ( y - nHeight - TextureBrowser_fontHeight( textureBrowser ) < originy )
1134                          && ( y > originy - textureBrowser.height ) ) {
1135                         // borders rules:
1136                         // if it's the current texture, draw a thick red line, else:
1137                         // shaders have a white border, simple textures don't
1138                         // if !texture_showinuse: (some textures displayed may not be in use)
1139                         // draw an additional square around with 0.5 1 0.5 color
1140                         if ( shader_equal( TextureBrowser_GetSelectedShader( textureBrowser ), shader->getName() ) ) {
1141                                 glLineWidth( 3 );
1142                                 if ( textureBrowser.m_rmbSelected ) {
1143                                         glColor3f( 0,0,1 );
1144                                 }
1145                                 else {
1146                                         glColor3f( 1,0,0 );
1147                                 }
1148                                 glDisable( GL_TEXTURE_2D );
1149
1150                                 glBegin( GL_LINE_LOOP );
1151                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1152                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1153                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1154                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1155                                 glEnd();
1156
1157                                 glEnable( GL_TEXTURE_2D );
1158                                 glLineWidth( 1 );
1159                         }
1160                         else
1161                         {
1162                                 glLineWidth( 1 );
1163                                 // shader border:
1164                                 if ( !shader->IsDefault() ) {
1165                                         glColor3f( 1,1,1 );
1166                                         glDisable( GL_TEXTURE_2D );
1167
1168                                         glBegin( GL_LINE_LOOP );
1169                                         glVertex2i( x - 1,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1170                                         glVertex2i( x - 1,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1171                                         glVertex2i( x + 1 + nWidth,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1172                                         glVertex2i( x + 1 + nWidth,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1173                                         glEnd();
1174                                         glEnable( GL_TEXTURE_2D );
1175                                 }
1176
1177                                 // highlight in-use textures
1178                                 if ( !textureBrowser.m_hideUnused && shader->IsInUse() ) {
1179                                         glColor3f( 0.5,1,0.5 );
1180                                         glDisable( GL_TEXTURE_2D );
1181                                         glBegin( GL_LINE_LOOP );
1182                                         glVertex2i( x - 3,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1183                                         glVertex2i( x - 3,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1184                                         glVertex2i( x + 3 + nWidth,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1185                                         glVertex2i( x + 3 + nWidth,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1186                                         glEnd();
1187                                         glEnable( GL_TEXTURE_2D );
1188                                 }
1189                         }
1190
1191                         // draw checkerboard for transparent textures
1192                         if ( g_TextureBrowser_enableAlpha )
1193                         {
1194                                 glDisable( GL_TEXTURE_2D );
1195                                 glBegin( GL_QUADS );
1196                                 int font_height = TextureBrowser_fontHeight( textureBrowser );
1197                                 for ( int i = 0; i < nHeight; i += 8 )
1198                                         for ( int j = 0; j < nWidth; j += 8 )
1199                                         {
1200                                                 unsigned char color = (i + j) / 8 % 2 ? 0x66 : 0x99;
1201                                                 glColor3ub( color, color, color );
1202                                                 int left = j;
1203                                                 int right = std::min(j+8, nWidth);
1204                                                 int top = i;
1205                                                 int bottom = std::min(i+8, nHeight);
1206                                                 glVertex2i(x + right, y - nHeight - font_height + top);
1207                                                 glVertex2i(x + left,  y - nHeight - font_height + top);
1208                                                 glVertex2i(x + left,  y - nHeight - font_height + bottom);
1209                                                 glVertex2i(x + right, y - nHeight - font_height + bottom);
1210                                         }
1211                                 glEnd();
1212                                 glEnable( GL_TEXTURE_2D );
1213                         }
1214
1215                         // Draw the texture
1216                         glBindTexture( GL_TEXTURE_2D, q->texture_number );
1217                         GlobalOpenGL_debugAssertNoErrors();
1218                         glColor3f( 1,1,1 );
1219                         glBegin( GL_QUADS );
1220                         glTexCoord2i( 0,0 );
1221                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) );
1222                         glTexCoord2i( 1,0 );
1223                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) );
1224                         glTexCoord2i( 1,1 );
1225                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1226                         glTexCoord2i( 0,1 );
1227                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1228                         glEnd();
1229
1230                         // draw the texture name
1231                         glDisable( GL_TEXTURE_2D );
1232                         glColor3f( 1,1,1 );
1233
1234                         glRasterPos2i( x, y - TextureBrowser_fontHeight( textureBrowser ) + 5 );
1235
1236                         // don't draw the directory name
1237                         const char* name = shader->getName();
1238                         name += strlen( name );
1239                         while ( name != shader->getName() && *( name - 1 ) != '/' && *( name - 1 ) != '\\' )
1240                                 name--;
1241
1242                         GlobalOpenGL().drawString( name );
1243                         glEnable( GL_TEXTURE_2D );
1244                 }
1245
1246                 //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4;
1247         }
1248
1249
1250         // reset the current texture
1251         glBindTexture( GL_TEXTURE_2D, 0 );
1252         //qglFinish();
1253 }
1254
1255 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser ){
1256         if ( textureBrowser.m_gl_widget != 0 ) {
1257                 gtk_widget_queue_draw( textureBrowser.m_gl_widget );
1258         }
1259 }
1260
1261
1262 void TextureBrowser_setScale( TextureBrowser& textureBrowser, std::size_t scale ){
1263         textureBrowser.m_textureScale = scale;
1264
1265         TextureBrowser_queueDraw( textureBrowser );
1266 }
1267
1268 void TextureBrowser_setUniformSize( TextureBrowser& textureBrowser, std::size_t scale ){
1269         textureBrowser.m_uniformTextureSize = scale;
1270
1271         TextureBrowser_queueDraw( textureBrowser );
1272 }
1273
1274
1275 void TextureBrowser_MouseWheel( TextureBrowser& textureBrowser, bool bUp ){
1276         int originy = TextureBrowser_getOriginY( textureBrowser );
1277
1278         if ( bUp ) {
1279                 originy += int(textureBrowser.m_mouseWheelScrollIncrement);
1280         }
1281         else
1282         {
1283                 originy -= int(textureBrowser.m_mouseWheelScrollIncrement);
1284         }
1285
1286         TextureBrowser_setOriginY( textureBrowser, originy );
1287 }
1288
1289 XmlTagBuilder TagBuilder;
1290
1291 enum
1292 {
1293         TAG_COLUMN,
1294         N_COLUMNS
1295 };
1296
1297 void BuildStoreAssignedTags( ui::ListStore store, const char* shader, TextureBrowser* textureBrowser ){
1298         GtkTreeIter iter;
1299
1300         gtk_list_store_clear( store );
1301
1302         std::vector<CopiedString> assigned_tags;
1303         TagBuilder.GetShaderTags( shader, assigned_tags );
1304
1305         for ( size_t i = 0; i < assigned_tags.size(); i++ )
1306         {
1307                 gtk_list_store_append( store, &iter );
1308                 gtk_list_store_set( store, &iter, TAG_COLUMN, assigned_tags[i].c_str(), -1 );
1309         }
1310 }
1311
1312 void BuildStoreAvailableTags(   ui::ListStore storeAvailable,
1313                                                                 ui::ListStore storeAssigned,
1314                                                                 const std::set<CopiedString>& allTags,
1315                                                                 TextureBrowser* textureBrowser ){
1316         GtkTreeIter iterAssigned;
1317         GtkTreeIter iterAvailable;
1318         std::set<CopiedString>::const_iterator iterAll;
1319         gchar* tag_assigned;
1320
1321         gtk_list_store_clear( storeAvailable );
1322
1323         bool row = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( storeAssigned ), &iterAssigned ) != 0;
1324
1325         if ( !row ) { // does the shader have tags assigned?
1326                 for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1327                 {
1328                         gtk_list_store_append( storeAvailable, &iterAvailable );
1329                         gtk_list_store_set( storeAvailable, &iterAvailable, TAG_COLUMN, ( *iterAll ).c_str(), -1 );
1330                 }
1331         }
1332         else
1333         {
1334                 while ( row ) // available tags = all tags - assigned tags
1335                 {
1336                         gtk_tree_model_get( GTK_TREE_MODEL( storeAssigned ), &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1337
1338                         for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1339                         {
1340                                 if ( strcmp( (char*)tag_assigned, ( *iterAll ).c_str() ) != 0 ) {
1341                                         gtk_list_store_append( storeAvailable, &iterAvailable );
1342                                         gtk_list_store_set( storeAvailable, &iterAvailable, TAG_COLUMN, ( *iterAll ).c_str(), -1 );
1343                                 }
1344                                 else
1345                                 {
1346                                         row = gtk_tree_model_iter_next( GTK_TREE_MODEL( storeAssigned ), &iterAssigned ) != 0;
1347
1348                                         if ( row ) {
1349                                                 gtk_tree_model_get( GTK_TREE_MODEL( storeAssigned ), &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1350                                         }
1351                                 }
1352                         }
1353                 }
1354         }
1355 }
1356
1357 gboolean TextureBrowser_button_press( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1358         if ( event->type == GDK_BUTTON_PRESS ) {
1359                 if ( event->button == 3 ) {
1360                         if ( GlobalTextureBrowser().m_tags ) {
1361                                 textureBrowser->m_rmbSelected = true;
1362                                 TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1363
1364                                 BuildStoreAssignedTags( textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser );
1365                                 BuildStoreAvailableTags( textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser );
1366                                 textureBrowser->m_heightChanged = true;
1367                                 textureBrowser->m_tag_frame.show();
1368
1369                                 process_gui();
1370
1371                                 TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1372                         }
1373                         else
1374                         {
1375                                 TextureBrowser_Tracking_MouseDown( *textureBrowser );
1376                         }
1377                 }
1378                 else if ( event->button == 1 ) {
1379                         TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1380
1381                         if ( GlobalTextureBrowser().m_tags ) {
1382                                 textureBrowser->m_rmbSelected = false;
1383                                 gtk_widget_hide( textureBrowser->m_tag_frame );
1384                         }
1385                 }
1386         }
1387         return FALSE;
1388 }
1389
1390 gboolean TextureBrowser_button_release( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1391         if ( event->type == GDK_BUTTON_RELEASE ) {
1392                 if ( event->button == 3 ) {
1393                         if ( !GlobalTextureBrowser().m_tags ) {
1394                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1395                         }
1396                 }
1397         }
1398         return FALSE;
1399 }
1400
1401 gboolean TextureBrowser_motion( ui::Widget widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1402         return FALSE;
1403 }
1404
1405 gboolean TextureBrowser_scroll( ui::Widget widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1406         if ( event->direction == GDK_SCROLL_UP ) {
1407                 TextureBrowser_MouseWheel( *textureBrowser, true );
1408         }
1409         else if ( event->direction == GDK_SCROLL_DOWN ) {
1410                 TextureBrowser_MouseWheel( *textureBrowser, false );
1411         }
1412         return FALSE;
1413 }
1414
1415 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1416         //globalOutputStream() << "vertical scroll\n";
1417         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1418 }
1419
1420 static void TextureBrowser_verticalScroll( GtkAdjustment *adjustment, TextureBrowser* textureBrowser ){
1421         textureBrowser->m_scrollAdjustment.value_changed( gtk_adjustment_get_value(adjustment) );
1422 }
1423
1424 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1425         if ( textureBrowser.m_showTextureScrollbar ) {
1426                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1427
1428                 totalHeight = std::max( totalHeight, textureBrowser.height );
1429
1430                 GtkAdjustment *vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1431
1432                 gtk_adjustment_set_value(vadjustment, -TextureBrowser_getOriginY( textureBrowser ));
1433                 gtk_adjustment_set_page_size(vadjustment, textureBrowser.height);
1434                 gtk_adjustment_set_page_increment(vadjustment, textureBrowser.height / 2);
1435                 gtk_adjustment_set_step_increment(vadjustment, 20);
1436                 gtk_adjustment_set_lower(vadjustment, 0);
1437                 gtk_adjustment_set_upper(vadjustment, totalHeight);
1438
1439                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1440         }
1441 }
1442
1443 gboolean TextureBrowser_size_allocate( ui::Widget widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1444         textureBrowser->width = allocation->width;
1445         textureBrowser->height = allocation->height;
1446         TextureBrowser_heightChanged( *textureBrowser );
1447         textureBrowser->m_originInvalid = true;
1448         TextureBrowser_queueDraw( *textureBrowser );
1449         return FALSE;
1450 }
1451
1452 gboolean TextureBrowser_expose( ui::Widget widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1453         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1454                 GlobalOpenGL_debugAssertNoErrors();
1455                 TextureBrowser_evaluateHeight( *textureBrowser );
1456                 Texture_Draw( *textureBrowser );
1457                 GlobalOpenGL_debugAssertNoErrors();
1458                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1459         }
1460         return FALSE;
1461 }
1462
1463
1464 TextureBrowser g_TextureBrowser;
1465
1466 TextureBrowser& GlobalTextureBrowser(){
1467         return g_TextureBrowser;
1468 }
1469
1470 bool TextureBrowser_hideUnused(){
1471         return g_TextureBrowser.m_hideUnused;
1472 }
1473
1474 void TextureBrowser_ToggleHideUnused(){
1475         if ( g_TextureBrowser.m_hideUnused ) {
1476                 TextureBrowser_SetHideUnused( g_TextureBrowser, false );
1477         }
1478         else
1479         {
1480                 TextureBrowser_SetHideUnused( g_TextureBrowser, true );
1481         }
1482 }
1483
1484 void TextureGroups_constructTreeModel( TextureGroups groups, GtkTreeStore* store ){
1485         // put the information from the old textures menu into a treeview
1486         GtkTreeIter iter, child;
1487
1488         TextureGroups::const_iterator i = groups.begin();
1489         while ( i != groups.end() )
1490         {
1491                 const char* dirName = ( *i ).c_str();
1492                 const char* firstUnderscore = strchr( dirName, '_' );
1493                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1494
1495                 TextureGroups::const_iterator next = i;
1496                 ++next;
1497                 if ( firstUnderscore != 0
1498                          && next != groups.end()
1499                          && string_equal_start( ( *next ).c_str(), dirRoot ) ) {
1500                         gtk_tree_store_append( store, &iter, NULL );
1501                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1502
1503                         // keep going...
1504                         while ( i != groups.end() && string_equal_start( ( *i ).c_str(), dirRoot ) )
1505                         {
1506                                 gtk_tree_store_append( store, &child, &iter );
1507                                 gtk_tree_store_set( store, &child, 0, ( *i ).c_str(), -1 );
1508                                 ++i;
1509                         }
1510                 }
1511                 else
1512                 {
1513                         gtk_tree_store_append( store, &iter, NULL );
1514                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1515                         ++i;
1516                 }
1517         }
1518 }
1519
1520 TextureGroups TextureGroups_constructTreeView(){
1521         TextureGroups groups;
1522
1523         if ( TextureBrowser_showWads() ) {
1524                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1525         }
1526         else
1527         {
1528                 // scan texture dirs and pak files only if not restricting to shaderlist
1529                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1530                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1531                 }
1532
1533                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1534         }
1535
1536         return groups;
1537 }
1538
1539 void TextureBrowser_constructTreeStore(){
1540         TextureGroups groups = TextureGroups_constructTreeView();
1541         GtkTreeStore* store = gtk_tree_store_new( 1, G_TYPE_STRING );
1542         TextureGroups_constructTreeModel( groups, store );
1543         std::set<CopiedString>::iterator iter;
1544
1545         GtkTreeModel* model = GTK_TREE_MODEL( store );
1546
1547         gtk_tree_view_set_model( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), model );
1548
1549         g_object_unref( G_OBJECT( store ) );
1550 }
1551
1552 void TextureBrowser_constructTreeStoreTags(){
1553         TextureGroups groups;
1554         GtkTreeStore* store = gtk_tree_store_new( 1, G_TYPE_STRING );
1555         GtkTreeModel* model = GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list );
1556
1557         gtk_tree_view_set_model( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), model );
1558
1559         g_object_unref( G_OBJECT( store ) );
1560 }
1561
1562 void TreeView_onRowActivated( GtkTreeView* treeview, GtkTreePath* path, GtkTreeViewColumn* col, gpointer userdata ){
1563         GtkTreeIter iter;
1564
1565         GtkTreeModel* model = gtk_tree_view_get_model( GTK_TREE_VIEW( treeview ) );
1566
1567         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1568                 gchar dirName[1024];
1569
1570                 gchar* buffer;
1571                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1572                 strcpy( dirName, buffer );
1573                 g_free( buffer );
1574
1575                 g_TextureBrowser.m_searchedTags = false;
1576
1577                 if ( !TextureBrowser_showWads() ) {
1578                         strcat( dirName, "/" );
1579                 }
1580
1581                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1582                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1583                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1584         }
1585 }
1586
1587 void TextureBrowser_createTreeViewTree(){
1588         g_TextureBrowser.m_treeViewTree = ui::TreeView();
1589         gtk_tree_view_set_enable_search( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), FALSE );
1590
1591         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), FALSE );
1592         g_signal_connect( g_TextureBrowser.m_treeViewTree, "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1593
1594         auto renderer = ui::CellRendererText();
1595         gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), -1, "", renderer, "text", 0, NULL );
1596
1597         TextureBrowser_constructTreeStore();
1598 }
1599
1600 void TextureBrowser_addTag();
1601 void TextureBrowser_renameTag();
1602 void TextureBrowser_deleteTag();
1603
1604 void TextureBrowser_createContextMenu( ui::Widget treeview, GdkEventButton *event ){
1605         ui::Widget menu = ui::Menu();
1606
1607         ui::Widget menuitem = ui::MenuItem( "Add tag" );
1608         g_signal_connect( menuitem, "activate", (GCallback)TextureBrowser_addTag, treeview );
1609         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1610
1611         menuitem = ui::MenuItem( "Rename tag" );
1612         g_signal_connect( menuitem, "activate", (GCallback)TextureBrowser_renameTag, treeview );
1613         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1614
1615         menuitem = ui::MenuItem( "Delete tag" );
1616         g_signal_connect( menuitem, "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1617         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1618
1619         gtk_widget_show_all( menu );
1620
1621         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1622                                         ( event != NULL ) ? event->button : 0,
1623                                         gdk_event_get_time( (GdkEvent*)event ) );
1624 }
1625
1626 gboolean TreeViewTags_onButtonPressed( ui::Widget treeview, GdkEventButton *event ){
1627         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1628                 GtkTreePath *path;
1629                 GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( treeview ) );
1630
1631                 if ( gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( treeview ), event->x, event->y, &path, NULL, NULL, NULL ) ) {
1632                         gtk_tree_selection_unselect_all( selection );
1633                         gtk_tree_selection_select_path( selection, path );
1634                         gtk_tree_path_free( path );
1635                 }
1636
1637                 TextureBrowser_createContextMenu( treeview, event );
1638                 return TRUE;
1639         }
1640         return FALSE;
1641 }
1642
1643 void TextureBrowser_createTreeViewTags(){
1644         g_TextureBrowser.m_treeViewTags = ui::TreeView();
1645         gtk_tree_view_set_enable_search( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), FALSE );
1646
1647         g_signal_connect( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1648
1649         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), FALSE );
1650
1651         auto renderer = ui::CellRendererText();
1652         gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), -1, "", renderer, "text", 0, NULL );
1653
1654         TextureBrowser_constructTreeStoreTags();
1655 }
1656
1657 ui::MenuItem TextureBrowser_constructViewMenu( ui::Menu menu ){
1658         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_View" ));
1659
1660         if ( g_Layout_enableDetachableMenus.m_value ) {
1661                 menu_tearoff( menu );
1662         }
1663
1664         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1665         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1666                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterMissing" );
1667         }
1668
1669         // hide notex and shadernotex on texture browser: no one wants to apply them
1670         create_check_menu_item_with_mnemonic( menu, "Hide Fallback", "FilterFallback" );
1671
1672         menu_separator( menu );
1673
1674         create_menu_item_with_mnemonic( menu, "Show All", "ShowAllTextures" );
1675
1676         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1677         if ( g_pGameDescription->mGameType == "doom3" || !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1678                 g_TextureBrowser.m_showShaders = true;
1679         }
1680         else
1681         {
1682                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1683         }
1684
1685         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1686                 create_check_menu_item_with_mnemonic( menu, "Shaders Only", "ToggleShowShaderlistOnly" );
1687         }
1688         if ( g_TextureBrowser.m_tags ) {
1689                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1690         }
1691
1692         menu_separator( menu );
1693         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1694         create_check_menu_item_with_mnemonic( menu, "Transparency", "EnableAlpha" );
1695
1696         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1697                 menu_separator( menu );
1698                 g_TextureBrowser.m_shader_info_item = ui::Widget(GTK_WIDGET( create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo" ) ));
1699                 gtk_widget_set_sensitive( g_TextureBrowser.m_shader_info_item, FALSE );
1700         }
1701
1702
1703         return textures_menu_item;
1704 }
1705
1706 ui::MenuItem TextureBrowser_constructToolsMenu( ui::Menu menu ){
1707         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_Tools" ));
1708
1709         if ( g_Layout_enableDetachableMenus.m_value ) {
1710                 menu_tearoff( menu );
1711         }
1712
1713         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1714         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1715
1716         return textures_menu_item;
1717 }
1718
1719 ui::MenuItem TextureBrowser_constructTagsMenu( ui::Menu menu ){
1720         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "T_ags" ));
1721
1722         if ( g_Layout_enableDetachableMenus.m_value ) {
1723                 menu_tearoff( menu );
1724         }
1725
1726         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1727         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1728         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1729         menu_separator( menu );
1730         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1731         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1732
1733         return textures_menu_item;
1734 }
1735
1736 gboolean TextureBrowser_tagMoveHelper( GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected ){
1737         g_assert( selected != NULL );
1738
1739         GtkTreeRowReference* rowref = gtk_tree_row_reference_new( model, path );
1740         *selected = g_slist_append( *selected, rowref );
1741
1742         return FALSE;
1743 }
1744
1745 void TextureBrowser_assignTags(){
1746         GSList* selected = NULL;
1747         GSList* node;
1748         gchar* tag_assigned;
1749
1750         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ) );
1751
1752         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1753
1754         if ( selected != NULL ) {
1755                 for ( node = selected; node != NULL; node = node->next )
1756                 {
1757                         GtkTreePath* path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1758
1759                         if ( path ) {
1760                                 GtkTreeIter iter;
1761
1762                                 if ( gtk_tree_model_get_iter( GTK_TREE_MODEL( g_TextureBrowser.m_available_store ), &iter, path ) ) {
1763                                         gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_available_store ), &iter, TAG_COLUMN, &tag_assigned, -1 );
1764                                         if ( !TagBuilder.CheckShaderTag( g_TextureBrowser.shader.c_str() ) ) {
1765                                                 // create a custom shader/texture entry
1766                                                 IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
1767                                                 CopiedString filename = ishader->getShaderFileName();
1768
1769                                                 if ( filename.empty() ) {
1770                                                         // it's a texture
1771                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, TEXTURE );
1772                                                 }
1773                                                 else {
1774                                                         // it's a shader
1775                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, SHADER );
1776                                                 }
1777                                                 ishader->DecRef();
1778                                         }
1779                                         TagBuilder.AddShaderTag( g_TextureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
1780
1781                                         gtk_list_store_remove( g_TextureBrowser.m_available_store, &iter );
1782                                         gtk_list_store_append( g_TextureBrowser.m_assigned_store, &iter );
1783                                         gtk_list_store_set( g_TextureBrowser.m_assigned_store, &iter, TAG_COLUMN, (char*)tag_assigned, -1 );
1784                                 }
1785                         }
1786                 }
1787
1788                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1789
1790                 // Save changes
1791                 TagBuilder.SaveXmlDoc();
1792         }
1793         g_slist_free( selected );
1794 }
1795
1796 void TextureBrowser_removeTags(){
1797         GSList* selected = NULL;
1798         GSList* node;
1799         gchar* tag;
1800
1801         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ) );
1802
1803         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1804
1805         if ( selected != NULL ) {
1806                 for ( node = selected; node != NULL; node = node->next )
1807                 {
1808                         GtkTreePath* path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1809
1810                         if ( path ) {
1811                                 GtkTreeIter iter;
1812
1813                                 if ( gtk_tree_model_get_iter( GTK_TREE_MODEL( g_TextureBrowser.m_assigned_store ), &iter, path ) ) {
1814                                         gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_assigned_store ), &iter, TAG_COLUMN, &tag, -1 );
1815                                         TagBuilder.DeleteShaderTag( g_TextureBrowser.shader.c_str(), tag );
1816                                         gtk_list_store_remove( g_TextureBrowser.m_assigned_store, &iter );
1817                                 }
1818                         }
1819                 }
1820
1821                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1822
1823                 // Update the "available tags list"
1824                 BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
1825
1826                 // Save changes
1827                 TagBuilder.SaveXmlDoc();
1828         }
1829         g_slist_free( selected );
1830 }
1831
1832 void TextureBrowser_buildTagList(){
1833         GtkTreeIter treeIter;
1834         gtk_list_store_clear( g_TextureBrowser.m_all_tags_list );
1835
1836         std::set<CopiedString>::iterator iter;
1837
1838         for ( iter = g_TextureBrowser.m_all_tags.begin(); iter != g_TextureBrowser.m_all_tags.end(); ++iter )
1839         {
1840                 gtk_list_store_append( g_TextureBrowser.m_all_tags_list, &treeIter );
1841                 gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &treeIter, TAG_COLUMN, ( *iter ).c_str(), -1 );
1842         }
1843 }
1844
1845 void TextureBrowser_searchTags(){
1846         GSList* selected = NULL;
1847         GSList* node;
1848         gchar* tag;
1849         char buffer[256];
1850         char tags_searched[256];
1851
1852         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
1853
1854         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1855
1856         if ( selected != NULL ) {
1857                 strcpy( buffer, "/root/*/*[tag='" );
1858                 strcpy( tags_searched, "[TAGS] " );
1859
1860                 for ( node = selected; node != NULL; node = node->next )
1861                 {
1862                         GtkTreePath* path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1863
1864                         if ( path ) {
1865                                 GtkTreeIter iter;
1866
1867                                 if ( gtk_tree_model_get_iter( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iter, path ) ) {
1868                                         gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iter, TAG_COLUMN, &tag, -1 );
1869
1870                                         strcat( buffer, tag );
1871                                         strcat( tags_searched, tag );
1872                                         if ( node != g_slist_last( node ) ) {
1873                                                 strcat( buffer, "' and tag='" );
1874                                                 strcat( tags_searched, ", " );
1875                                         }
1876                                 }
1877                         }
1878                 }
1879
1880                 strcat( buffer, "']" );
1881
1882                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1883
1884                 g_TextureBrowser.m_found_shaders.clear(); // delete old list
1885                 TagBuilder.TagSearch( buffer, g_TextureBrowser.m_found_shaders );
1886
1887                 if ( !g_TextureBrowser.m_found_shaders.empty() ) { // found something
1888                         size_t shaders_found = g_TextureBrowser.m_found_shaders.size();
1889
1890                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
1891                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
1892
1893                         std::set<CopiedString>::iterator iter;
1894
1895                         for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
1896                         {
1897                                 std::string path = ( *iter ).c_str();
1898                                 size_t pos = path.find_last_of( "/", path.size() );
1899                                 std::string name = path.substr( pos + 1, path.size() );
1900                                 path = path.substr( 0, pos + 1 );
1901                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
1902                         }
1903                 }
1904                 g_TextureBrowser.m_searchedTags = true;
1905                 g_TextureBrowser_currentDirectory = tags_searched;
1906
1907                 g_TextureBrowser.m_nTotalHeight = 0;
1908                 TextureBrowser_setOriginY( g_TextureBrowser, 0 );
1909                 TextureBrowser_heightChanged( g_TextureBrowser );
1910                 TextureBrowser_updateTitle();
1911         }
1912         g_slist_free( selected );
1913 }
1914
1915 void TextureBrowser_toggleSearchButton(){
1916         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ) );
1917
1918         if ( page == 0 ) { // tag page
1919                 gtk_widget_show_all( g_TextureBrowser.m_search_button );
1920         }
1921         else {
1922                 gtk_widget_hide( g_TextureBrowser.m_search_button );
1923         }
1924 }
1925
1926 void TextureBrowser_constructTagNotebook(){
1927         g_TextureBrowser.m_tag_notebook = ui::Widget(gtk_notebook_new());
1928         ui::Widget labelTags = ui::Label( "Tags" );
1929         ui::Widget labelTextures = ui::Label( "Textures" );
1930
1931         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tree, labelTextures );
1932         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tags, labelTags );
1933
1934         g_signal_connect( G_OBJECT( g_TextureBrowser.m_tag_notebook ), "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
1935
1936         gtk_widget_show_all( g_TextureBrowser.m_tag_notebook );
1937 }
1938
1939 void TextureBrowser_constructSearchButton(){
1940         ui::Widget image = ui::Widget(gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR ));
1941         g_TextureBrowser.m_search_button = ui::Button();
1942         g_signal_connect( G_OBJECT( g_TextureBrowser.m_search_button ), "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
1943         gtk_widget_set_tooltip_text(g_TextureBrowser.m_search_button, "Search with selected tags");
1944         gtk_container_add( GTK_CONTAINER( g_TextureBrowser.m_search_button ), image );
1945 }
1946
1947 void TextureBrowser_checkTagFile(){
1948         const char SHADERTAG_FILE[] = "shadertags.xml";
1949         CopiedString default_filename, rc_filename;
1950         StringOutputStream stream( 256 );
1951
1952         stream << LocalRcPath_get();
1953         stream << SHADERTAG_FILE;
1954         rc_filename = stream.c_str();
1955
1956         if ( file_exists( rc_filename.c_str() ) ) {
1957                 g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
1958
1959                 if ( g_TextureBrowser.m_tags ) {
1960                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
1961                 }
1962         }
1963         else
1964         {
1965                 // load default tagfile
1966                 stream.clear();
1967                 stream << g_pGameDescription->mGameToolsPath.c_str();
1968                 stream << SHADERTAG_FILE;
1969                 default_filename = stream.c_str();
1970
1971                 if ( file_exists( default_filename.c_str() ) ) {
1972                         g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
1973
1974                         if ( g_TextureBrowser.m_tags ) {
1975                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
1976                         }
1977                 }
1978                 else
1979                 {
1980                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
1981                 }
1982         }
1983 }
1984
1985 void TextureBrowser_SetNotex(){
1986         StringOutputStream name( 256 );
1987         name << GlobalRadiant().getAppPath() << "bitmaps/" NOTEX_BASENAME ".png";
1988         g_notex = name.c_str();
1989
1990         name = NULL;
1991         name << GlobalRadiant().getAppPath() << "bitmaps/" SHADERNOTEX_BASENAME " .png";
1992         g_shadernotex = name.c_str();
1993 }
1994
1995 ui::Widget TextureBrowser_constructWindow( ui::Window toplevel ){
1996         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
1997         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
1998         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
1999         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
2000
2001         TextureBrowser_checkTagFile();
2002         TextureBrowser_SetNotex();
2003
2004         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, TextureBrowser_activeShadersChanged>( g_TextureBrowser ) );
2005
2006         g_TextureBrowser.m_parent = toplevel;
2007
2008         ui::Widget table = ui::Table( 3, 3, FALSE );
2009         ui::Widget frame_table;
2010         ui::Widget vbox = ui::VBox( FALSE, 0 );
2011         gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0 );
2012         vbox.show();
2013
2014         ui::Widget menu_bar;
2015
2016         { // menu bar
2017                 menu_bar = ui::Widget(gtk_menu_bar_new());
2018                 auto menu_view = ui::Menu();
2019                 auto view_item = TextureBrowser_constructViewMenu( menu_view );
2020                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
2021                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), view_item );
2022
2023                 auto menu_tools = ui::Menu();
2024                 auto tools_item = TextureBrowser_constructToolsMenu( menu_tools );
2025                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
2026                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tools_item );
2027
2028                 gtk_table_attach( GTK_TABLE( table ), menu_bar, 0, 3, 0, 1, GTK_FILL, GTK_SHRINK, 0, 0 );
2029                 menu_bar.show();
2030         }
2031         { // Texture TreeView
2032                 g_TextureBrowser.m_scr_win_tree = ui::ScrolledWindow();
2033                 gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tree ), 0 );
2034
2035                 // vertical only scrolling for treeview
2036                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2037
2038                 g_TextureBrowser.m_scr_win_tree.show();
2039
2040                 TextureBrowser_createTreeViewTree();
2041
2042                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), GTK_WIDGET( g_TextureBrowser.m_treeViewTree ) );
2043                 g_TextureBrowser.m_treeViewTree.show();
2044         }
2045         { // gl_widget scrollbar
2046                 ui::Widget w = ui::Widget(gtk_vscrollbar_new( ui::Adjustment( 0,0,0,1,1,0 ) ));
2047                 gtk_table_attach( GTK_TABLE( table ), w, 2, 3, 1, 2, GTK_SHRINK, GTK_FILL, 0, 0 );
2048                 w.show();
2049                 g_TextureBrowser.m_texture_scroll = w;
2050
2051                 GtkAdjustment *vadjustment = gtk_range_get_adjustment( GTK_RANGE( g_TextureBrowser.m_texture_scroll ) );
2052                 g_signal_connect( G_OBJECT( vadjustment ), "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &g_TextureBrowser );
2053
2054                 widget_set_visible( g_TextureBrowser.m_texture_scroll, g_TextureBrowser.m_showTextureScrollbar );
2055         }
2056         { // gl_widget
2057                 g_TextureBrowser.m_gl_widget = ui::Widget(glwidget_new( FALSE ));
2058                 g_object_ref( g_TextureBrowser.m_gl_widget );
2059
2060                 gtk_widget_set_events( g_TextureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
2061                 gtk_widget_set_can_focus( g_TextureBrowser.m_gl_widget, true );
2062
2063                 gtk_table_attach_defaults( GTK_TABLE( table ), g_TextureBrowser.m_gl_widget, 1, 2, 1, 2 );
2064                 g_TextureBrowser.m_gl_widget.show();
2065
2066                 g_TextureBrowser.m_sizeHandler = g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &g_TextureBrowser );
2067                 g_TextureBrowser.m_exposeHandler = g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "expose_event", G_CALLBACK( TextureBrowser_expose ), &g_TextureBrowser );
2068
2069                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &g_TextureBrowser );
2070                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &g_TextureBrowser );
2071                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &g_TextureBrowser );
2072                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &g_TextureBrowser );
2073         }
2074
2075         // tag stuff
2076         if ( g_TextureBrowser.m_tags ) {
2077                 { // fill tag GtkListStore
2078                         g_TextureBrowser.m_all_tags_list = ui::ListStore(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2079                         GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_all_tags_list );
2080                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2081
2082                         TagBuilder.GetAllTags( g_TextureBrowser.m_all_tags );
2083                         TextureBrowser_buildTagList();
2084                 }
2085                 { // tag menu bar
2086                         auto menu_tags = ui::Menu();
2087                         auto tags_item = TextureBrowser_constructTagsMenu( menu_tags );
2088                         gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
2089                         gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tags_item );
2090                 }
2091                 { // Tag TreeView
2092                         g_TextureBrowser.m_scr_win_tags = ui::ScrolledWindow();
2093                         gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tags ), 0 );
2094
2095                         // vertical only scrolling for treeview
2096                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2097
2098                         TextureBrowser_createTreeViewTags();
2099
2100                         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
2101                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2102
2103                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), GTK_WIDGET( g_TextureBrowser.m_treeViewTags ) );
2104                         g_TextureBrowser.m_treeViewTags.show();
2105                 }
2106                 { // Texture/Tag notebook
2107                         TextureBrowser_constructTagNotebook();
2108                         gtk_box_pack_start( GTK_BOX( vbox ), g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2109                 }
2110                 { // Tag search button
2111                         TextureBrowser_constructSearchButton();
2112                         gtk_box_pack_end( GTK_BOX( vbox ), g_TextureBrowser.m_search_button, FALSE, FALSE, 0 );
2113                 }
2114                 { // Tag frame
2115                         frame_table = ui::Table( 3, 3, FALSE );
2116
2117                         g_TextureBrowser.m_tag_frame = ui::Frame( "Tag assignment" );
2118                         gtk_frame_set_label_align( GTK_FRAME( g_TextureBrowser.m_tag_frame ), 0.5, 0.5 );
2119                         gtk_frame_set_shadow_type( GTK_FRAME( g_TextureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2120
2121                         gtk_table_attach( GTK_TABLE( table ), g_TextureBrowser.m_tag_frame, 1, 3, 2, 3, GTK_FILL, GTK_SHRINK, 0, 0 );
2122
2123                         frame_table.show();
2124
2125                         gtk_container_add( GTK_CONTAINER( g_TextureBrowser.m_tag_frame ), frame_table );
2126                 }
2127                 { // assigned tag list
2128                         ui::Widget scrolled_win = ui::ScrolledWindow();
2129                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2130                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2131
2132                         g_TextureBrowser.m_assigned_store = ui::ListStore(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2133
2134                         GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_assigned_store );
2135                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2136
2137                         auto renderer = ui::CellRendererText();
2138
2139                         g_TextureBrowser.m_assigned_tree = ui::TreeView(ui::TreeModel( GTK_TREE_MODEL( g_TextureBrowser.m_assigned_store ) ));
2140                         g_object_unref( G_OBJECT( g_TextureBrowser.m_assigned_store ) );
2141                         g_signal_connect( g_TextureBrowser.m_assigned_tree, "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2142                         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ), FALSE );
2143
2144                         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ) );
2145                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2146
2147                         GtkTreeViewColumn* column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2148                         gtk_tree_view_append_column( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ), column );
2149                         g_TextureBrowser.m_assigned_tree.show();
2150
2151                         scrolled_win.show();
2152                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_WIDGET( g_TextureBrowser.m_assigned_tree ) );
2153
2154                         gtk_table_attach( GTK_TABLE( frame_table ), scrolled_win, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0 );
2155                 }
2156                 { // available tag list
2157                         ui::Widget scrolled_win = ui::ScrolledWindow();
2158                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2159                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2160
2161                         g_TextureBrowser.m_available_store = ui::ListStore(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2162                         GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_available_store );
2163                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2164
2165                         auto renderer = ui::CellRendererText();
2166
2167                         g_TextureBrowser.m_available_tree = ui::TreeView(ui::TreeModel( GTK_TREE_MODEL( g_TextureBrowser.m_available_store ) ));
2168                         g_object_unref( G_OBJECT( g_TextureBrowser.m_available_store ) );
2169                         g_signal_connect( g_TextureBrowser.m_available_tree, "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2170                         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ), FALSE );
2171
2172                         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ) );
2173                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2174
2175                         GtkTreeViewColumn* column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2176                         gtk_tree_view_append_column( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ), column );
2177                         g_TextureBrowser.m_available_tree.show();
2178
2179                         scrolled_win.show();
2180                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_WIDGET( g_TextureBrowser.m_available_tree ) );
2181
2182                         gtk_table_attach( GTK_TABLE( frame_table ), scrolled_win, 2, 3, 1, 3, GTK_FILL, GTK_FILL, 0, 0 );
2183                 }
2184                 { // tag arrow buttons
2185                         ui::Widget m_btn_left = ui::Button();
2186                         ui::Widget m_btn_right = ui::Button();
2187                         ui::Widget m_arrow_left = ui::Widget(gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ));
2188                         ui::Widget m_arrow_right = ui::Widget(gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT ));
2189                         gtk_container_add( GTK_CONTAINER( m_btn_left ), m_arrow_left );
2190                         gtk_container_add( GTK_CONTAINER( m_btn_right ), m_arrow_right );
2191
2192                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2193                         gtk_widget_set_size_request( m_arrow_left, -1, 68 );
2194                         gtk_widget_set_size_request( m_arrow_right, -1, 68 );
2195
2196                         gtk_table_attach( GTK_TABLE( frame_table ), m_btn_left, 1, 2, 1, 2, GTK_SHRINK, GTK_EXPAND, 0, 0 );
2197                         gtk_table_attach( GTK_TABLE( frame_table ), m_btn_right, 1, 2, 2, 3, GTK_SHRINK, GTK_EXPAND, 0, 0 );
2198
2199                         g_signal_connect( G_OBJECT( m_btn_left ), "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2200                         g_signal_connect( G_OBJECT( m_btn_right ), "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2201
2202                         m_btn_left.show();
2203                         m_btn_right.show();
2204                         m_arrow_left.show();
2205                         m_arrow_right.show();
2206                 }
2207                 { // tag fram labels
2208                         ui::Widget m_lbl_assigned = ui::Label( "Assigned" );
2209                         ui::Widget m_lbl_unassigned = ui::Label( "Available" );
2210
2211                         gtk_table_attach( GTK_TABLE( frame_table ), m_lbl_assigned, 0, 1, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0 );
2212                         gtk_table_attach( GTK_TABLE( frame_table ), m_lbl_unassigned, 2, 3, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0 );
2213
2214                         m_lbl_assigned.show();
2215                         m_lbl_unassigned.show();
2216                 }
2217         }
2218         else { // no tag support, show the texture tree only
2219                 gtk_box_pack_start( GTK_BOX( vbox ), g_TextureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2220         }
2221
2222         // TODO do we need this?
2223         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2224
2225         return table;
2226 }
2227
2228 void TextureBrowser_destroyWindow(){
2229         GlobalShaderSystem().setActiveShadersChangedNotify( Callback() );
2230
2231         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_sizeHandler );
2232         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_exposeHandler );
2233
2234         g_object_unref( g_TextureBrowser.m_gl_widget );
2235 }
2236
2237 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2238         return textureBrowser.color_textureback;
2239 }
2240
2241 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2242         textureBrowser.color_textureback = colour;
2243         TextureBrowser_queueDraw( textureBrowser );
2244 }
2245
2246 void TextureBrowser_selectionHelper( GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected ){
2247         g_assert( selected != NULL );
2248
2249         gchar* name;
2250         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2251         *selected = g_slist_append( *selected, name );
2252 }
2253
2254 void TextureBrowser_shaderInfo(){
2255         const char* name = TextureBrowser_GetSelectedShader( g_TextureBrowser );
2256         IShader* shader = QERApp_Shader_ForName( name );
2257
2258         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2259
2260         shader->DecRef();
2261 }
2262
2263 void TextureBrowser_addTag(){
2264         CopiedString tag;
2265
2266         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2267
2268         if ( result == eIDOK && !tag.empty() ) {
2269                 GtkTreeIter iter, iter2;
2270                 g_TextureBrowser.m_all_tags.insert( tag.c_str() );
2271                 gtk_list_store_append( g_TextureBrowser.m_available_store, &iter );
2272                 gtk_list_store_set( g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2273
2274                 // Select the currently added tag in the available list
2275                 GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ) );
2276                 gtk_tree_selection_select_iter( selection, &iter );
2277
2278                 gtk_list_store_append( g_TextureBrowser.m_all_tags_list, &iter2 );
2279                 gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &iter2, TAG_COLUMN, tag.c_str(), -1 );
2280         }
2281 }
2282
2283 void TextureBrowser_renameTag(){
2284         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2285            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2286            we need to count the number of selected rows first and use
2287            gtk_tree_selection_selected_foreach() then to go through the list of selected
2288            rows (which always containins a single row).
2289          */
2290
2291         GSList* selected = NULL;
2292
2293         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
2294         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2295
2296         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2297                 CopiedString newTag;
2298                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2299
2300                 if ( result == eIDOK && !newTag.empty() ) {
2301                         GtkTreeIter iterList;
2302                         gchar* rowTag;
2303                         gchar* oldTag = (char*)selected->data;
2304
2305                         bool row = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterList ) != 0;
2306
2307                         while ( row )
2308                         {
2309                                 gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterList, TAG_COLUMN, &rowTag, -1 );
2310
2311                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2312                                         gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2313                                 }
2314                                 row = gtk_tree_model_iter_next( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterList ) != 0;
2315                         }
2316
2317                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2318
2319                         g_TextureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2320                         g_TextureBrowser.m_all_tags.insert( newTag );
2321
2322                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2323                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2324                 }
2325         }
2326         else
2327         {
2328                 ui::Widget(GTK_WIDGET( g_TextureBrowser.m_parent )).alert( "Select a single tag for renaming." );
2329         }
2330 }
2331
2332 void TextureBrowser_deleteTag(){
2333         GSList* selected = NULL;
2334
2335         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
2336         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2337
2338         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2339                 auto result = ui::Widget(GTK_WIDGET( g_TextureBrowser.m_parent )).alert( "Are you sure you want to delete the selected tag?", "Delete Tag", ui::alert_type::YESNO, ui::alert_icon::Question );
2340
2341                 if ( result == ui::alert_response::YES ) {
2342                         GtkTreeIter iterSelected;
2343                         gchar *rowTag;
2344
2345                         gchar* tagSelected = (char*)selected->data;
2346
2347                         bool row = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterSelected ) != 0;
2348
2349                         while ( row )
2350                         {
2351                                 gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterSelected, TAG_COLUMN, &rowTag, -1 );
2352
2353                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2354                                         gtk_list_store_remove( g_TextureBrowser.m_all_tags_list, &iterSelected );
2355                                         break;
2356                                 }
2357                                 row = gtk_tree_model_iter_next( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterSelected ) != 0;
2358                         }
2359
2360                         TagBuilder.DeleteTag( tagSelected );
2361                         g_TextureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2362
2363                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2364                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2365                 }
2366         }
2367         else {
2368                 ui::Widget(GTK_WIDGET( g_TextureBrowser.m_parent )).alert( "Select a single tag for deletion." );
2369         }
2370 }
2371
2372 void TextureBrowser_copyTag(){
2373         g_TextureBrowser.m_copied_tags.clear();
2374         TagBuilder.GetShaderTags( g_TextureBrowser.shader.c_str(), g_TextureBrowser.m_copied_tags );
2375 }
2376
2377 void TextureBrowser_pasteTag(){
2378         IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
2379         CopiedString shader = g_TextureBrowser.shader.c_str();
2380
2381         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2382                 CopiedString shaderFile = ishader->getShaderFileName();
2383                 if ( shaderFile.empty() ) {
2384                         // it's a texture
2385                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2386                 }
2387                 else
2388                 {
2389                         // it's a shader
2390                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2391                 }
2392
2393                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2394                 {
2395                         TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2396                 }
2397         }
2398         else
2399         {
2400                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2401                 {
2402                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str() ) ) {
2403                                 // the tag doesn't exist - let's add it
2404                                 TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2405                         }
2406                 }
2407         }
2408
2409         ishader->DecRef();
2410
2411         TagBuilder.SaveXmlDoc();
2412         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, shader.c_str(), &g_TextureBrowser );
2413         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2414 }
2415
2416 void TextureBrowser_RefreshShaders(){
2417         ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2418         GlobalShaderSystem().refresh();
2419         UpdateAllWindows();
2420         GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(GlobalTextureBrowser().m_treeViewTree));
2421         GtkTreeModel* model = NULL;
2422         GtkTreeIter iter;
2423         if ( gtk_tree_selection_get_selected (selection, &model, &iter) )
2424         {
2425                 gchar dirName[1024];
2426
2427                 gchar* buffer;
2428                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
2429                 strcpy( dirName, buffer );
2430                 g_free( buffer );
2431                 if ( !TextureBrowser_showWads() ) {
2432                         strcat( dirName, "/" );
2433                 }
2434                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
2435                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2436         }
2437 }
2438
2439 void TextureBrowser_ToggleShowShaders(){
2440         g_TextureBrowser.m_showShaders ^= 1;
2441         g_TextureBrowser.m_showshaders_item.update();
2442         TextureBrowser_queueDraw( g_TextureBrowser );
2443 }
2444
2445 void TextureBrowser_ToggleShowShaderListOnly(){
2446         g_TextureBrowser_shaderlistOnly ^= 1;
2447         g_TextureBrowser.m_showshaderlistonly_item.update();
2448
2449         TextureBrowser_constructTreeStore();
2450 }
2451
2452 void TextureBrowser_showAll(){
2453         g_TextureBrowser_currentDirectory = "";
2454         g_TextureBrowser.m_searchedTags = false;
2455         TextureBrowser_heightChanged( g_TextureBrowser );
2456         TextureBrowser_updateTitle();
2457 }
2458
2459 void TextureBrowser_showUntagged(){
2460         auto result = ui::Widget(GTK_WIDGET( g_TextureBrowser.m_parent )).alert( "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", ui::alert_type::YESNO, ui::alert_icon::Warning );
2461
2462         if ( result == ui::alert_response::YES ) {
2463                 g_TextureBrowser.m_found_shaders.clear();
2464                 TagBuilder.GetUntagged( g_TextureBrowser.m_found_shaders );
2465                 std::set<CopiedString>::iterator iter;
2466
2467                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2468
2469                 for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
2470                 {
2471                         std::string path = ( *iter ).c_str();
2472                         size_t pos = path.find_last_of( "/", path.size() );
2473                         std::string name = path.substr( pos + 1, path.size() );
2474                         path = path.substr( 0, pos + 1 );
2475                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2476                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2477                 }
2478
2479                 g_TextureBrowser_currentDirectory = "Untagged";
2480                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2481                 TextureBrowser_heightChanged( g_TextureBrowser );
2482                 TextureBrowser_updateTitle();
2483         }
2484 }
2485
2486 void TextureBrowser_FixedSize(){
2487         g_TextureBrowser_fixedSize ^= 1;
2488         GlobalTextureBrowser().m_fixedsize_item.update();
2489         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2490 }
2491
2492 void TextureBrowser_FilterMissing(){
2493         g_TextureBrowser_filterMissing ^= 1;
2494         GlobalTextureBrowser().m_filternotex_item.update();
2495         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2496         TextureBrowser_RefreshShaders();
2497 }
2498
2499 void TextureBrowser_FilterFallback(){
2500         g_TextureBrowser_filterFallback ^= 1;
2501         GlobalTextureBrowser().m_hidenotex_item.update();
2502         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2503         TextureBrowser_RefreshShaders();
2504 }
2505
2506 void TextureBrowser_EnableAlpha(){
2507         g_TextureBrowser_enableAlpha ^= 1;
2508         GlobalTextureBrowser().m_enablealpha_item.update();
2509         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2510 }
2511
2512 void TextureBrowser_exportTitle( const StringImportCallback& importer ){
2513         StringOutputStream buffer( 64 );
2514         buffer << "Textures: ";
2515         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2516                 buffer << g_TextureBrowser_currentDirectory.c_str();
2517         }
2518         else
2519         {
2520                 buffer << "all";
2521         }
2522         importer( buffer.c_str() );
2523 }
2524
2525
2526 void TextureScaleImport( TextureBrowser& textureBrowser, int value ){
2527         switch ( value )
2528         {
2529         case 0:
2530                 TextureBrowser_setScale( textureBrowser, 10 );
2531                 break;
2532         case 1:
2533                 TextureBrowser_setScale( textureBrowser, 25 );
2534                 break;
2535         case 2:
2536                 TextureBrowser_setScale( textureBrowser, 50 );
2537                 break;
2538         case 3:
2539                 TextureBrowser_setScale( textureBrowser, 100 );
2540                 break;
2541         case 4:
2542                 TextureBrowser_setScale( textureBrowser, 200 );
2543                 break;
2544         }
2545 }
2546 typedef ReferenceCaller1<TextureBrowser, int, TextureScaleImport> TextureScaleImportCaller;
2547
2548 void TextureScaleExport( TextureBrowser& textureBrowser, const IntImportCallback& importer ){
2549         switch ( textureBrowser.m_textureScale )
2550         {
2551         case 10:
2552                 importer( 0 );
2553                 break;
2554         case 25:
2555                 importer( 1 );
2556                 break;
2557         case 50:
2558                 importer( 2 );
2559                 break;
2560         case 100:
2561                 importer( 3 );
2562                 break;
2563         case 200:
2564                 importer( 4 );
2565                 break;
2566         }
2567 }
2568 typedef ReferenceCaller1<TextureBrowser, const IntImportCallback&, TextureScaleExport> TextureScaleExportCaller;
2569
2570
2571 void UniformTextureSizeImport( TextureBrowser& textureBrowser, int value ){
2572
2573         if ( value > 16 )
2574                 TextureBrowser_setUniformSize( textureBrowser, value );
2575 }
2576 typedef ReferenceCaller1<TextureBrowser, int, UniformTextureSizeImport> UniformTextureSizeImportCaller;
2577
2578 void TextureBrowser_constructPreferences( PreferencesPage& page ){
2579         page.appendCheckBox(
2580                 "", "Texture scrollbar",
2581                 TextureBrowserImportShowScrollbarCaller( GlobalTextureBrowser() ),
2582                 BoolExportCaller( GlobalTextureBrowser().m_showTextureScrollbar )
2583                 );
2584         {
2585                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
2586                 page.appendCombo(
2587                         "Texture Thumbnail Scale",
2588                         STRING_ARRAY_RANGE( texture_scale ),
2589                         IntImportCallback( TextureScaleImportCaller( GlobalTextureBrowser() ) ),
2590                         IntExportCallback( TextureScaleExportCaller( GlobalTextureBrowser() ) )
2591                         );
2592         }
2593         page.appendSpinner(
2594                 "Texture Thumbnail Size",
2595                 GlobalTextureBrowser().m_uniformTextureSize,
2596                 GlobalTextureBrowser().m_uniformTextureSize,
2597                 16, 8192
2598         );
2599         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
2600         {
2601                 const char* startup_shaders[] = { "None", TextureBrowser_getComonShadersName() };
2602                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
2603         }
2604 }
2605 void TextureBrowser_constructPage( PreferenceGroup& group ){
2606         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
2607         TextureBrowser_constructPreferences( page );
2608 }
2609 void TextureBrowser_registerPreferencesPage(){
2610         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, TextureBrowser_constructPage>() );
2611 }
2612
2613
2614 #include "preferencesystem.h"
2615 #include "stringio.h"
2616
2617 typedef ReferenceCaller1<TextureBrowser, std::size_t, TextureBrowser_setScale> TextureBrowserSetScaleCaller;
2618
2619
2620
2621 void TextureClipboard_textureSelected( const char* shader );
2622
2623 void TextureBrowser_Construct(){
2624         GlobalCommands_insert( "ShaderInfo", FreeCaller<TextureBrowser_shaderInfo>() );
2625         GlobalCommands_insert( "ShowUntagged", FreeCaller<TextureBrowser_showUntagged>() );
2626         GlobalCommands_insert( "AddTag", FreeCaller<TextureBrowser_addTag>() );
2627         GlobalCommands_insert( "RenameTag", FreeCaller<TextureBrowser_renameTag>() );
2628         GlobalCommands_insert( "DeleteTag", FreeCaller<TextureBrowser_deleteTag>() );
2629         GlobalCommands_insert( "CopyTag", FreeCaller<TextureBrowser_copyTag>() );
2630         GlobalCommands_insert( "PasteTag", FreeCaller<TextureBrowser_pasteTag>() );
2631         GlobalCommands_insert( "RefreshShaders", FreeCaller<VFS_Refresh>() );
2632         GlobalToggles_insert( "ShowInUse", FreeCaller<TextureBrowser_ToggleHideUnused>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_hideunused_item ), Accelerator( 'U' ) );
2633         GlobalCommands_insert( "ShowAllTextures", FreeCaller<TextureBrowser_showAll>(), Accelerator( 'A', (GdkModifierType)GDK_CONTROL_MASK ) );
2634         GlobalCommands_insert( "ToggleTextures", FreeCaller<TextureBrowser_toggleShow>(), Accelerator( 'T' ) );
2635         GlobalToggles_insert( "ToggleShowShaders", FreeCaller<TextureBrowser_ToggleShowShaders>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showshaders_item ) );
2636         GlobalToggles_insert( "ToggleShowShaderlistOnly", FreeCaller<TextureBrowser_ToggleShowShaderListOnly>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showshaderlistonly_item ) );
2637         GlobalToggles_insert( "FixedSize", FreeCaller<TextureBrowser_FixedSize>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_fixedsize_item ) );
2638         GlobalToggles_insert( "FilterMissing", FreeCaller<TextureBrowser_FilterMissing>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_filternotex_item ) );
2639         GlobalToggles_insert( "FilterFallback", FreeCaller<TextureBrowser_FilterFallback>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_hidenotex_item ) );
2640         GlobalToggles_insert( "EnableAlpha", FreeCaller<TextureBrowser_EnableAlpha>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_enablealpha_item ) );
2641
2642         GlobalPreferenceSystem().registerPreference( "TextureScale",
2643                                                                                                  makeSizeStringImportCallback( TextureBrowserSetScaleCaller( g_TextureBrowser ) ),
2644                                                                                                  SizeExportStringCaller( g_TextureBrowser.m_textureScale )
2645                                                                                                  );
2646         GlobalPreferenceSystem().registerPreference( "UniformTextureSize",
2647                                                                                                  makeIntStringImportCallback(UniformTextureSizeImportCaller(g_TextureBrowser)),
2648                                                                                                  IntExportStringCaller(g_TextureBrowser.m_uniformTextureSize) );
2649         GlobalPreferenceSystem().registerPreference( "TextureScrollbar",
2650                                                                                                  makeBoolStringImportCallback( TextureBrowserImportShowScrollbarCaller( g_TextureBrowser ) ),
2651                                                                                                  BoolExportStringCaller( GlobalTextureBrowser().m_showTextureScrollbar )
2652                                                                                                  );
2653         GlobalPreferenceSystem().registerPreference( "ShowShaders", BoolImportStringCaller( GlobalTextureBrowser().m_showShaders ), BoolExportStringCaller( GlobalTextureBrowser().m_showShaders ) );
2654         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", BoolImportStringCaller( g_TextureBrowser_shaderlistOnly ), BoolExportStringCaller( g_TextureBrowser_shaderlistOnly ) );
2655         GlobalPreferenceSystem().registerPreference( "FixedSize", BoolImportStringCaller( g_TextureBrowser_fixedSize ), BoolExportStringCaller( g_TextureBrowser_fixedSize ) );
2656         GlobalPreferenceSystem().registerPreference( "FilterMissing", BoolImportStringCaller( g_TextureBrowser_filterMissing ), BoolExportStringCaller( g_TextureBrowser_filterMissing ) );
2657         GlobalPreferenceSystem().registerPreference( "EnableAlpha", BoolImportStringCaller( g_TextureBrowser_enableAlpha ), BoolExportStringCaller( g_TextureBrowser_enableAlpha ) );
2658         GlobalPreferenceSystem().registerPreference( "LoadShaders", IntImportStringCaller( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ), IntExportStringCaller( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ) );
2659         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", SizeImportStringCaller( GlobalTextureBrowser().m_mouseWheelScrollIncrement ), SizeExportStringCaller( GlobalTextureBrowser().m_mouseWheelScrollIncrement ) );
2660         GlobalPreferenceSystem().registerPreference( "SI_Colors0", Vector3ImportStringCaller( GlobalTextureBrowser().color_textureback ), Vector3ExportStringCaller( GlobalTextureBrowser().color_textureback ) );
2661
2662         g_TextureBrowser.shader = texdef_name_default();
2663
2664         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, TextureBrowser_queueDraw>( g_TextureBrowser ) );
2665
2666         TextureBrowser_registerPreferencesPage();
2667
2668         GlobalShaderSystem().attach( g_ShadersObserver );
2669
2670         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
2671 }
2672 void TextureBrowser_Destroy(){
2673         GlobalShaderSystem().detach( g_ShadersObserver );
2674
2675         Textures_setModeChangedNotify( Callback() );
2676 }