Codebase list jd-gui / 0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstream app / src / main / java / org / jd / gui / controller / SearchInConstantPoolsController.java
0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstream

Tree @0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstream (Download .tar.gz)

SearchInConstantPoolsController.java @0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstreamraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*
 * Copyright (c) 2008-2019 Emmanuel Dupuy.
 * This project is distributed under the GPLv3 license.
 * This is a Copyleft license that gives the user the right to use,
 * copy and modify the code freely for non-commercial purposes.
 */

package org.jd.gui.controller;

import org.jd.gui.api.API;
import org.jd.gui.api.feature.IndexesChangeListener;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.api.model.Type;
import org.jd.gui.model.container.DelegatingFilterContainer;
import org.jd.gui.service.type.TypeFactoryService;
import org.jd.gui.spi.TypeFactory;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.function.TriConsumer;
import org.jd.gui.view.SearchInConstantPoolsView;

import javax.swing.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.regex.Pattern;

public class SearchInConstantPoolsController implements IndexesChangeListener {
    protected static final int CACHE_MAX_ENTRIES = 5*20*9;

    protected API api;
    protected ScheduledExecutorService executor;

    protected JFrame mainFrame;
    protected SearchInConstantPoolsView searchInConstantPoolsView;
    protected Map<String, Map<String, Collection>> cache;
    protected Set<DelegatingFilterContainer> delegatingFilterContainers = new HashSet<>();
    protected Collection<Future<Indexes>> collectionOfFutureIndexes;
    protected Consumer<URI> openCallback;
    protected long indexesHashCode = 0L;

    @SuppressWarnings("unchecked")
    public SearchInConstantPoolsController(API api, ScheduledExecutorService executor, JFrame mainFrame) {
        this.api = api;
        this.executor = executor;
        this.mainFrame = mainFrame;
        // Create UI
        this.searchInConstantPoolsView = new SearchInConstantPoolsView(
            api, mainFrame,
            new BiConsumer<String, Integer>() {
                @Override public void accept(String pattern, Integer flags) { updateTree(pattern, flags); }
            },
            new TriConsumer<URI, String, Integer>() {
                @Override public void accept(URI uri, String pattern, Integer flags) { onTypeSelected(uri, pattern, flags); }
            }
        );
        // Create result cache
        this.cache = new LinkedHashMap<String, Map<String, Collection>>(CACHE_MAX_ENTRIES*3/2, 0.7f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, Map<String, Collection>> eldest) {
                return size() > CACHE_MAX_ENTRIES;
            }
        };
    }

    public void show(Collection<Future<Indexes>> collectionOfFutureIndexes, Consumer<URI> openCallback) {
        // Init attributes
        this.collectionOfFutureIndexes = collectionOfFutureIndexes;
        this.openCallback = openCallback;
        // Refresh view
        long hashCode = collectionOfFutureIndexes.hashCode();
        if (hashCode != indexesHashCode) {
            // List of indexes has changed
            updateTree(searchInConstantPoolsView.getPattern(), searchInConstantPoolsView.getFlags());
            indexesHashCode = hashCode;
        }
        // Show
        searchInConstantPoolsView.show();
    }

    @SuppressWarnings("unchecked")
    protected void updateTree(String pattern, int flags) {
        delegatingFilterContainers.clear();

        executor.execute(() -> {
            // Waiting the end of indexation...
            searchInConstantPoolsView.showWaitCursor();

            int matchingTypeCount = 0;
            int patternLength = pattern.length();

            if (patternLength > 0) {
                try {
                    for (Future<Indexes> futureIndexes : collectionOfFutureIndexes) {
                        if (futureIndexes.isDone()) {
                            Indexes indexes = futureIndexes.get();
                            HashSet<Container.Entry> matchingEntries = new HashSet<>();
                            // Find matched entries
                            filter(indexes, pattern, flags, matchingEntries);

                            if (!matchingEntries.isEmpty()) {
                                // Search root container with first matching entry
                                Container.Entry parentEntry = matchingEntries.iterator().next();
                                Container container = null;

                                while (parentEntry.getContainer().getRoot() != null) {
                                    container = parentEntry.getContainer();
                                    parentEntry = container.getRoot().getParent();
                                }

                                // TODO In a future release, display matching strings, types, inner-types, fields and methods, not only matching files
                                matchingEntries = getOuterEntries(matchingEntries);

                                matchingTypeCount += matchingEntries.size();

                                // Create a filtered container
                                delegatingFilterContainers.add(new DelegatingFilterContainer(container, matchingEntries));
                            }
                        }
                    }
                } catch (Exception e) {
                    assert ExceptionUtil.printStackTrace(e);
                }
            }

            final int count = matchingTypeCount;

            searchInConstantPoolsView.hideWaitCursor();
            searchInConstantPoolsView.updateTree(delegatingFilterContainers, count);
        });
    }

    protected HashSet<Container.Entry> getOuterEntries(Set<Container.Entry> matchingEntries) {
        HashMap<Container.Entry, Container.Entry> innerTypeEntryToOuterTypeEntry = new HashMap<>();
        HashSet<Container.Entry> matchingOuterEntriesSet = new HashSet<>();

        for (Container.Entry entry : matchingEntries) {
            TypeFactory typeFactory = TypeFactoryService.getInstance().get(entry);

            if (typeFactory != null) {
                Type type = typeFactory.make(api, entry, null);

                if ((type != null) && (type.getOuterName() != null)) {
                    Container.Entry outerTypeEntry = innerTypeEntryToOuterTypeEntry.get(entry);

                    if (outerTypeEntry == null) {
                        HashMap<String, Container.Entry> typeNameToEntry = new HashMap<>();
                        HashMap<String, String> innerTypeNameToOuterTypeName = new HashMap<>();

                        // Populate "typeNameToEntry" and "innerTypeNameToOuterTypeName"
                        for (Container.Entry e : entry.getParent().getChildren()) {
                            typeFactory = TypeFactoryService.getInstance().get(e);

                            if (typeFactory != null) {
                                type = typeFactory.make(api, e, null);

                                if (type != null) {
                                    typeNameToEntry.put(type.getName(), e);
                                    if (type.getOuterName() != null) {
                                        innerTypeNameToOuterTypeName.put(type.getName(), type.getOuterName());
                                    }
                                }
                            }
                        }

                        // Search outer type entries and populate "innerTypeEntryToOuterTypeEntry"
                        for (Map.Entry<String, String> e : innerTypeNameToOuterTypeName.entrySet()) {
                            Container.Entry innerTypeEntry = typeNameToEntry.get(e.getKey());

                            if (innerTypeEntry != null) {
                                String outerTypeName = e.getValue();

                                for (;;) {
                                    String typeName = innerTypeNameToOuterTypeName.get(outerTypeName);
                                    if (typeName != null) {
                                        outerTypeName = typeName;
                                    } else {
                                        break;
                                    }
                                }

                                outerTypeEntry = typeNameToEntry.get(outerTypeName);

                                if (outerTypeEntry != null) {
                                    innerTypeEntryToOuterTypeEntry.put(innerTypeEntry, outerTypeEntry);
                                }
                            }
                        }

                        // Get outer type entry
                        outerTypeEntry = innerTypeEntryToOuterTypeEntry.get(entry);

                        if (outerTypeEntry == null) {
                            outerTypeEntry = entry;
                        }
                    }

                    matchingOuterEntriesSet.add(outerTypeEntry);
                } else{
                    matchingOuterEntriesSet.add(entry);
                }
            }
        }

        return matchingOuterEntriesSet;
    }

    protected void filter(Indexes indexes, String pattern, int flags, Set<Container.Entry> matchingEntries) {
        boolean declarations = ((flags & SearchInConstantPoolsView.SEARCH_DECLARATION) != 0);
        boolean references = ((flags & SearchInConstantPoolsView.SEARCH_REFERENCE) != 0);

        if ((flags & SearchInConstantPoolsView.SEARCH_TYPE) != 0) {
            if (declarations)
                match(indexes, "typeDeclarations", pattern,
                      SearchInConstantPoolsController::matchTypeEntriesWithChar,
                      SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
            if (references)
                match(indexes, "typeReferences", pattern,
                      SearchInConstantPoolsController::matchTypeEntriesWithChar,
                      SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
        }

        if ((flags & SearchInConstantPoolsView.SEARCH_CONSTRUCTOR) != 0) {
            if (declarations)
                match(indexes, "constructorDeclarations", pattern,
                      SearchInConstantPoolsController::matchTypeEntriesWithChar,
                      SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
            if (references)
                match(indexes, "constructorReferences", pattern,
                      SearchInConstantPoolsController::matchTypeEntriesWithChar,
                      SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
        }

        if ((flags & SearchInConstantPoolsView.SEARCH_METHOD) != 0) {
            if (declarations)
                match(indexes, "methodDeclarations", pattern,
                      SearchInConstantPoolsController::matchWithChar,
                      SearchInConstantPoolsController::matchWithString, matchingEntries);
            if (references)
                match(indexes, "methodReferences", pattern,
                      SearchInConstantPoolsController::matchWithChar,
                      SearchInConstantPoolsController::matchWithString, matchingEntries);
        }

        if ((flags & SearchInConstantPoolsView.SEARCH_FIELD) != 0) {
            if (declarations)
                match(indexes, "fieldDeclarations", pattern,
                      SearchInConstantPoolsController::matchWithChar,
                      SearchInConstantPoolsController::matchWithString, matchingEntries);
            if (references)
                match(indexes, "fieldReferences", pattern,
                      SearchInConstantPoolsController::matchWithChar,
                      SearchInConstantPoolsController::matchWithString, matchingEntries);
        }

        if ((flags & SearchInConstantPoolsView.SEARCH_STRING) != 0) {
            if (declarations || references)
                match(indexes, "strings", pattern,
                      SearchInConstantPoolsController::matchWithChar,
                      SearchInConstantPoolsController::matchWithString, matchingEntries);
        }

        if ((flags & SearchInConstantPoolsView.SEARCH_MODULE) != 0) {
            if (declarations)
                match(indexes, "javaModuleDeclarations", pattern,
                        SearchInConstantPoolsController::matchWithChar,
                        SearchInConstantPoolsController::matchWithString, matchingEntries);
            if (references)
                match(indexes, "javaModuleReferences", pattern,
                        SearchInConstantPoolsController::matchWithChar,
                        SearchInConstantPoolsController::matchWithString, matchingEntries);
        }
    }

    @SuppressWarnings("unchecked")
    protected void match(Indexes indexes, String indexName, String pattern,
                         BiFunction<Character, Map<String, Collection>, Map<String, Collection>> matchWithCharFunction,
                         BiFunction<String, Map<String, Collection>, Map<String, Collection>> matchWithStringFunction,
                         Set<Container.Entry> matchingEntries) {
        int patternLength = pattern.length();

        if (patternLength > 0) {
            String key = String.valueOf(indexes.hashCode()) + "***" + indexName + "***" + pattern;
            Map<String, Collection> matchedEntries = cache.get(key);

            if (matchedEntries == null) {
                Map<String, Collection> index = indexes.getIndex(indexName);

                if (index != null) {
                    if (patternLength == 1) {
                        matchedEntries = matchWithCharFunction.apply(pattern.charAt(0), index);
                    } else {
                        String lastKey = key.substring(0, key.length() - 1);
                        Map<String, Collection> lastMatchedTypes = cache.get(lastKey);
                        if (lastMatchedTypes != null) {
                            matchedEntries = matchWithStringFunction.apply(pattern, lastMatchedTypes);
                        } else {
                            matchedEntries = matchWithStringFunction.apply(pattern, index);
                        }
                    }
                }

                // Cache matchingEntries
                cache.put(key, matchedEntries);
            }

            if (matchedEntries != null) {
                for (Collection<Container.Entry> entries : matchedEntries.values()) {
                    matchingEntries.addAll(entries);
                }
            }
        }
    }

    protected static Map<String, Collection> matchTypeEntriesWithChar(char c, Map<String, Collection> index) {
        if ((c == '*') || (c == '?')) {
            return index;
        } else {
            Map<String, Collection> map = new HashMap<>();

            for (String typeName : index.keySet()) {
                // Search last package separator
                int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
                int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
                int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);

                if ((lastIndex < typeName.length()) && (typeName.charAt(lastIndex) == c)) {
                    map.put(typeName, index.get(typeName));
                }
            }

            return map;
        }
    }

    protected static Map<String, Collection> matchTypeEntriesWithString(String pattern, Map<String, Collection> index) {
        Pattern p = createPattern(pattern);
        Map<String, Collection> map = new HashMap<>();

        for (String typeName : index.keySet()) {
            // Search last package separator
            int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
            int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
            int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);

            if (p.matcher(typeName.substring(lastIndex)).matches()) {
                map.put(typeName, index.get(typeName));
            }
        }

        return map;
    }

    protected static Map<String, Collection> matchWithChar(char c, Map<String, Collection> index) {
        if ((c == '*') || (c == '?')) {
            return index;
        } else {
            Map<String, Collection> map = new HashMap<>();

            for (String key : index.keySet()) {
                if (!key.isEmpty() && (key.charAt(0) == c)) {
                    map.put(key, index.get(key));
                }
            }

            return map;
        }
    }

    protected static Map<String, Collection> matchWithString(String pattern, Map<String, Collection> index) {
        Pattern p = createPattern(pattern);
        Map<String, Collection> map = new HashMap<>();

        for (String key : index.keySet()) {
            if (p.matcher(key).matches()) {
                map.put(key, index.get(key));
            }
        }

        return map;
    }

    /**
     * Create a simple regular expression
     *
     * Rules:
     *  '*'        matchTypeEntries 0 ou N characters
     *  '?'        matchTypeEntries 1 character
     */
    protected static Pattern createPattern(String pattern) {
        int patternLength = pattern.length();
        StringBuilder sbPattern = new StringBuilder(patternLength * 2);

        for (int i = 0; i < patternLength; i++) {
            char c = pattern.charAt(i);

            if (c == '*') {
                sbPattern.append(".*");
            } else if (c == '?') {
                sbPattern.append('.');
            } else if (c == '.') {
                sbPattern.append("\\.");
            } else {
                sbPattern.append(c);
            }
        }

        sbPattern.append(".*");

        return Pattern.compile(sbPattern.toString());
    }

    protected void onTypeSelected(URI uri, String pattern, int flags) {
        // Open the single entry uri
        Container.Entry entry = null;

        for (DelegatingFilterContainer container : delegatingFilterContainers) {
            entry = container.getEntry(uri);
            if (entry != null)
                break;
        }

        if (entry != null) {
            StringBuilder sbPattern = new StringBuilder(200 + pattern.length());

            sbPattern.append("highlightPattern=");
            sbPattern.append(pattern);
            sbPattern.append("&highlightFlags=");

            if ((flags & SearchInConstantPoolsView.SEARCH_DECLARATION) != 0)
                sbPattern.append('d');
            if ((flags & SearchInConstantPoolsView.SEARCH_REFERENCE) != 0)
                sbPattern.append('r');
            if ((flags & SearchInConstantPoolsView.SEARCH_TYPE) != 0)
                sbPattern.append('t');
            if ((flags & SearchInConstantPoolsView.SEARCH_CONSTRUCTOR) != 0)
                sbPattern.append('c');
            if ((flags & SearchInConstantPoolsView.SEARCH_METHOD) != 0)
                sbPattern.append('m');
            if ((flags & SearchInConstantPoolsView.SEARCH_FIELD) != 0)
                sbPattern.append('f');
            if ((flags & SearchInConstantPoolsView.SEARCH_STRING) != 0)
                sbPattern.append('s');
            if ((flags & SearchInConstantPoolsView.SEARCH_MODULE) != 0)
                sbPattern.append('M');

            // TODO In a future release, add 'highlightScope' to display search results in correct type and inner-type
            // def type = TypeFactoryService.instance.get(entry)?.make(api, entry, null)
            // if (type) {
            //     sbPattern.append('&highlightScope=')
            //     sbPattern.append(type.name)
            //
            //     def query = sbPattern.toString()
            //     def outerPath = UriUtil.getOuterPath(collectionOfFutureIndexes, entry, type)
            //
            //     openClosure(new URI(entry.uri.scheme, entry.uri.host, outerPath, query, null))
            // } else {
                String query = sbPattern.toString();
                URI u = entry.getUri();

                try {
                    openCallback.accept(new URI(u.getScheme(), u.getHost(), u.getPath(), query, null));
                } catch (URISyntaxException e) {
                    assert ExceptionUtil.printStackTrace(e);
                }
            // }
        }
    }

    // --- IndexesChangeListener --- //
    public void indexesChanged(Collection<Future<Indexes>> collectionOfFutureIndexes) {
        if (searchInConstantPoolsView.isVisible()) {
            // Update the list of containers
            this.collectionOfFutureIndexes = collectionOfFutureIndexes;
            // And refresh
            updateTree(searchInConstantPoolsView.getPattern(), searchInConstantPoolsView.getFlags());
        }
    }
}