aboutsummaryrefslogtreecommitdiff
path: root/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateViewPage.java
blob: faa9561cbba9df1e68ebb7f8af9b7542b992bf1b (plain)
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
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ide.eclipse.gltrace.editors;

import com.android.ide.eclipse.gltrace.GlTracePlugin;
import com.android.ide.eclipse.gltrace.editors.GLCallGroups.GLCallNode;
import com.android.ide.eclipse.gltrace.model.GLCall;
import com.android.ide.eclipse.gltrace.model.GLTrace;
import com.android.ide.eclipse.gltrace.state.GLState;
import com.android.ide.eclipse.gltrace.state.IGLProperty;
import com.android.ide.eclipse.gltrace.state.StatePrettyPrinter;
import com.android.ide.eclipse.gltrace.state.transforms.IStateTransform;
import com.google.common.base.Charsets;
import com.google.common.io.Files;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ILock;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.Page;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * A tree view of the OpenGL state. It listens to the current GLCall that is selected
 * in the Function Trace view, and updates its view to reflect the state as of the selected call.
 */
public class StateViewPage extends Page implements ISelectionListener, ISelectionProvider {
    public static final String ID = "com.android.ide.eclipse.gltrace.views.GLState"; //$NON-NLS-1$
    private static String sLastUsedPath;
    private static final ILock sGlStateLock = Job.getJobManager().newLock();

    private GLTrace mTrace;
    private List<GLCall> mGLCalls;

    /** OpenGL State as of call {@link #mCurrentStateIndex}. */
    private IGLProperty mState;
    private int mCurrentStateIndex;

    private String[] TREE_PROPERTIES = { "Name", "Value" };
    private TreeViewer mTreeViewer;
    private StateLabelProvider mLabelProvider;

    public StateViewPage(GLTrace trace) {
        setInput(trace);
    }

    public void setInput(GLTrace trace) {
        mTrace = trace;
        if (trace != null) {
            mGLCalls = trace.getGLCalls();
        } else {
            mGLCalls = null;
        }

        mState = GLState.createDefaultState();
        mCurrentStateIndex = -1;

        if (mTreeViewer != null) {
            mTreeViewer.setInput(mState);
            mTreeViewer.refresh();
        }
    }

    @Override
    public void createControl(Composite parent) {
        final Tree tree = new Tree(parent, SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL);
        GridDataFactory.fillDefaults().grab(true, true).applyTo(tree);

        tree.setHeaderVisible(true);
        tree.setLinesVisible(true);
        tree.setLayoutData(new GridData(GridData.FILL_BOTH));

        TreeColumn col1 = new TreeColumn(tree, SWT.LEFT);
        col1.setText(TREE_PROPERTIES[0]);
        col1.setWidth(200);

        TreeColumn col2 = new TreeColumn(tree, SWT.LEFT);
        col2.setText(TREE_PROPERTIES[1]);
        col2.setWidth(200);

        mTreeViewer = new TreeViewer(tree);
        mTreeViewer.setContentProvider(new StateContentProvider());
        mLabelProvider = new StateLabelProvider();
        mTreeViewer.setLabelProvider(mLabelProvider);
        mTreeViewer.setInput(mState);
        mTreeViewer.refresh();

        final IToolBarManager manager = getSite().getActionBars().getToolBarManager();
        manager.add(new Action("Save to File",
                PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
                        ISharedImages.IMG_ETOOL_SAVEAS_EDIT)) {
            @Override
            public void run() {
                saveCurrentState();
            }
        });
    }

    private void saveCurrentState() {
        final Shell shell = mTreeViewer.getTree().getShell();
        FileDialog fd = new FileDialog(shell, SWT.SAVE);
        fd.setFilterExtensions(new String[] { "*.txt" });
        if (sLastUsedPath != null) {
            fd.setFilterPath(sLastUsedPath);
        }

        String path = fd.open();
        if (path == null) {
            return;
        }

        File f = new File(path);
        sLastUsedPath = f.getParent();

        // export state to f
        StatePrettyPrinter pp = new StatePrettyPrinter();
        synchronized (sGlStateLock) {
            mState.prettyPrint(pp);
        }

        try {
            Files.write(pp.toString(), f, Charsets.UTF_8);
        } catch (IOException e) {
            ErrorDialog.openError(shell,
                    "Export GL State",
                    "Unexpected error while writing GL state to file.",
                    new Status(Status.ERROR, GlTracePlugin.PLUGIN_ID, e.toString()));
        }
    }

    @Override
    public void init(IPageSite pageSite) {
        super.init(pageSite);
        pageSite.getPage().addSelectionListener(this);
    }

    @Override
    public void dispose() {
        getSite().getPage().removeSelectionListener(this);
        super.dispose();
    }

    @Override
    public void selectionChanged(IWorkbenchPart part, ISelection selection) {
        if (!(part instanceof GLFunctionTraceViewer)) {
            return;
        }

        if (((GLFunctionTraceViewer) part).getTrace() != mTrace) {
            return;
        }

        if (!(selection instanceof TreeSelection)) {
            return;
        }

        GLCall selectedCall = null;

        Object data = ((TreeSelection) selection).getFirstElement();
        if (data instanceof GLCallNode) {
            selectedCall = ((GLCallNode) data).getCall();
        }

        if (selectedCall == null) {
            return;
        }

        final int selectedCallIndex = selectedCall.getIndex();

        // Creation of texture images takes a few seconds on the first run. So run
        // the update task as an Eclipse job.
        Job job = new Job("Updating GL State") {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                Set<IGLProperty> changedProperties = null;

                try {
                    sGlStateLock.acquire();
                    changedProperties = updateState(mCurrentStateIndex,
                            selectedCallIndex);
                    mCurrentStateIndex = selectedCallIndex;
                } catch (Exception e) {
                    GlTracePlugin.getDefault().logMessage(
                            "Unexpected error while updating GL State.");
                    GlTracePlugin.getDefault().logMessage(e.getMessage());
                    return new Status(Status.ERROR,
                            GlTracePlugin.PLUGIN_ID,
                            "Unexpected error while updating GL State.",
                            e);
                } finally {
                    sGlStateLock.release();
                }

                mLabelProvider.setChangedProperties(changedProperties);
                Display.getDefault().syncExec(new Runnable() {
                    @Override
                    public void run() {
                        if (!mTreeViewer.getTree().isDisposed()) {
                            mTreeViewer.refresh();
                        }
                    }
                });

                return Status.OK_STATUS;
            }
        };
        job.setPriority(Job.SHORT);
        job.schedule();
    }

    @Override
    public Control getControl() {
        if (mTreeViewer == null) {
            return null;
        }

        return mTreeViewer.getControl();
    }

    @Override
    public void setFocus() {
    }

    /**
     * Update GL state from GL call at fromIndex to the call at toIndex.
     * If fromIndex < toIndex, the GL state will be updated by applying all the transformations
     * corresponding to calls from (fromIndex + 1) to toIndex (inclusive).
     * If fromIndex > toIndex, the GL state will be updated by reverting all the calls from
     * fromIndex (inclusive) to (toIndex + 1).
     * @return GL state properties that changed as a result of this update.
     */
    private Set<IGLProperty> updateState(int fromIndex, int toIndex) {
        assert fromIndex >= -1 && fromIndex < mGLCalls.size();
        assert toIndex >= 0 && toIndex < mGLCalls.size();

        if (fromIndex < toIndex) {
            return applyTransformations(fromIndex, toIndex);
        } else if (fromIndex > toIndex) {
            return revertTransformations(fromIndex, toIndex);
        } else {
            return Collections.emptySet();
        }
    }

    private Set<IGLProperty> applyTransformations(int fromIndex, int toIndex) {
        int setSizeHint = 3 * (toIndex - fromIndex) + 10;
        Set<IGLProperty> changedProperties = new HashSet<IGLProperty>(setSizeHint);

        for (int i = fromIndex + 1; i <= toIndex; i++) {
            GLCall call = mGLCalls.get(i);
            for (IStateTransform f : call.getStateTransformations()) {
                try {
                    f.apply(mState);
                    IGLProperty changedProperty = f.getChangedProperty(mState);
                    if (changedProperty != null) {
                        changedProperties.addAll(getHierarchy(changedProperty));
                    }
                } catch (Exception e) {
                    GlTracePlugin.getDefault().logMessage("Error applying transformations for "
                            + call);
                    GlTracePlugin.getDefault().logMessage(e.toString());
                }
            }
        }

        return changedProperties;
    }

    private Set<IGLProperty> revertTransformations(int fromIndex, int toIndex) {
        int setSizeHint = 3 * (fromIndex - toIndex) + 10;
        Set<IGLProperty> changedProperties = new HashSet<IGLProperty>(setSizeHint);

        for (int i = fromIndex; i > toIndex; i--) {
            List<IStateTransform> transforms = mGLCalls.get(i).getStateTransformations();
            // When reverting transformations, iterate from the last to first so that the reversals
            // are performed in the correct sequence.
            for (int j = transforms.size() - 1; j >= 0; j--) {
                IStateTransform f = transforms.get(j);
                f.revert(mState);

                IGLProperty changedProperty = f.getChangedProperty(mState);
                if (changedProperty != null) {
                    changedProperties.addAll(getHierarchy(changedProperty));
                }
            }
        }

        return changedProperties;
    }

    /**
     * Obtain the list of properties starting from the provided property up to
     * the root of GL state.
     */
    private List<IGLProperty> getHierarchy(IGLProperty changedProperty) {
        List<IGLProperty> changedProperties = new ArrayList<IGLProperty>(5);
        changedProperties.add(changedProperty);

        // add the entire parent chain until we reach the root
        IGLProperty prop = changedProperty;
        while ((prop = prop.getParent()) != null) {
            changedProperties.add(prop);
        }

        return changedProperties;
    }

    @Override
    public void addSelectionChangedListener(ISelectionChangedListener listener) {
        mTreeViewer.addSelectionChangedListener(listener);
    }

    @Override
    public ISelection getSelection() {
        return mTreeViewer.getSelection();
    }

    @Override
    public void removeSelectionChangedListener(ISelectionChangedListener listener) {
        mTreeViewer.removeSelectionChangedListener(listener);
    }

    @Override
    public void setSelection(ISelection selection) {
        mTreeViewer.setSelection(selection);
    }
}